diff --git a/lib/strings.js b/lib/strings.js index c9d31c4..3663da1 100644 --- a/lib/strings.js +++ b/lib/strings.js @@ -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, @@ -95,4 +106,5 @@ module.exports = { fileExt, parsePath, trimLines, + validateBracketBalance, }; diff --git a/metautil.d.ts b/metautil.d.ts index f892bd1..73398c4 100644 --- a/metautil.d.ts +++ b/metautil.d.ts @@ -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