Array.reduce Mutating State Outside Is Not Recommended?
Why is mutating variables outside .reduce() method considered bad practice? In the example below I am mutating a variable declared outside from inside the reduce method. Why is it
Solution 1:
Why is mutating variables outside
.reduce()
method considered bad practice?
Because you are mixing the functional with the imperative approach. Keep it to a single paradigm instead of confusing everyone.
You would go with
either
reduce
with a pure callback and no side effectsfunctionstep({max: oldMax, counter: oldCounter}, char) { const counter = oldCounter + (char=="(") - (char==")"); const max = counter > oldMax ? counter : oldMax; return {max, counter}; } functionmaxParensLevel(string) { assert(hasBalancedParens(string)); const {max, counter} = string.split("").reduce(step, {max:0, counter:0}); returnmax; }
or a simple loop and two mutable variables
functionmaxParensLevel(string) { assert(hasBalancedParens(string)); let max = 0; let counter = 0; for (const char of string.split("")) { if (char == "(") counter++; elseif (char == ")") counter--;if (counter > max) max = counter; } returnmax; }
but not both.
Solution 2:
See @JordanRunning comment:
"If you do that, why bother using reduce at all? If your output is via side-effects you might as well be using forEach"
I was about to say the same. And here is a version of the function without an external dependency:
functionbalanceParens(string) {
let res = string.split("").reduce((state, char) => {
// Handle if parens open and close out of orderif (state.counter < 0) {
return state;
}
// Add 1 for each open in orderif (char === "(") {
if (++state.counter > state.max) {
state.max = state.counter;
}
return state;
}
// subtract 1 for each close in orderif (char === ")") {
state.counter = --state.counter;
return state;
}
// handle use case if char is not a parenreturn state;
}, {max: 0, counter: 0});
console.log("Max depth was :", res.max);
return !res.counter;
}
console.log(balanceParens("((()(((())))))((((()))))"));
Post a Comment for "Array.reduce Mutating State Outside Is Not Recommended?"