Why are mutating variables outside the method .reduce()considered bad practice?
Because you mix functionality with an imperative approach. Keep it in a single paradigm, not confuse everyone.
Would you go with
either reducewith a clean callback and no side effects
function step({max: oldMax, counter: oldCounter}, char) {
const counter = oldCounter + (char=="(") - (char==")");
const max = counter > oldMax ? counter : oldMax;
return {max, counter};
}
function maxParensLevel(string) {
assert(hasBalancedParens(string));
const {max, counter} = string.split("").reduce(step, {max:0, counter:0});
return max;
}
or a simple loop and two mutable variables
function maxParensLevel(string) {
assert(hasBalancedParens(string));
let max = 0;
let counter = 0;
for (const char of string.split("")) {
if (char == "(")
counter++;
else if (char == ")")
counter--;
if (counter > max)
max = counter;
}
return max;
}
but not both.
source
share