Balanced brackets: Difference between revisions
→Functional JS: Generalised the code a little. (Other bracket types, mixed strings)
(→Functional JS: Refactored to a 'find' function with a Maybe return type.) |
(→Functional JS: Generalised the code a little. (Other bracket types, mixed strings)) |
||
Line 3,359:
'use strict';
// findUnbalancedBracket :: String -> String -> Maybe Int
const findUnbalancedBracket = strBrackets => strHaystack => {
const
openBracket = strBrackets[0],
closeBracket = strBrackets[1];
const go = (xs, iDepth, iCharPosn) =>
// iDepth: initial nesting depth (0 = closed)
Line 3,366 ⟶ 3,369:
0 < xs.length ? (() => {
const
h = xs[0],
tail = xs.slice(1),
iNext = iDepth + (
strBrackets.includes(h) ? (
openBracket === xs[0] ? (
1
) : -1
) : 0
);
return 0 > iNext ? (
Just(iCharPosn) // Unmatched closing bracket.
Line 3,378 ⟶ 3,388:
Just(iCharPosn)
) : Nothing();
return go(
};
Line 3,399 ⟶ 3,409:
' '.repeat(1 + iUnMatched) + '^'
)(
findUnbalancedBracket('[]')(s)
);
}).join('\n')
|