Skip to content

Commit

Permalink
Add bracket balance validation
Browse files Browse the repository at this point in the history
Bracket balance validation used in metarhia/metaschema/#454

Add bracket balance validation

Bracket balance validation used in metarhia/metaschema#454
  • Loading branch information
aliendrew committed Aug 10, 2023
1 parent 1826b95 commit 32538a1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/strings.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,17 @@ const trimLines = (s) => {
return chunks.filter((d) => d !== '').join('\n');
};

const validateBracketBalance = (s, brackets = '()[]{}<>') => {
const stack = [];
for (const bracket of s) {
const index = brackets.indexOf(bracket);
if (index === -1) continue;
if (index % 2 === 0) stack.push(index + 1);
else if (stack.pop() !== index) return false;
}
return stack.length === 0;
};

module.exports = {
replace,
between,
Expand All @@ -95,4 +106,5 @@ module.exports = {
fileExt,
parsePath,
trimLines,
validateBracketBalance,
};
1 change: 1 addition & 0 deletions metautil.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ export function isConstant(s: string): boolean;
export function fileExt(fileName: string): string;
export function parsePath(relPath: string): Strings;
export function trimLines(s: string): string;
export function validateBracketBalance(s: string, brackets?: string): boolean;

// Submodule: units

Expand Down

0 comments on commit 32538a1

Please sign in to comment.