扩展 Javascript array.reduce helper 方法的使用



Background

我正在学习一门关于 Udemy 的课程,该课程介绍了 ES6 的所有功能。在其中一课中,讲师谈到了如何使用化简辅助方法解决流行的平衡括号面试问题。

我可以在没有reduce方法的情况下解决这个问题。尽管使用 reduce 方法,它确实可以在更少的代码中完成工作。我之前在一次采访中被要求找到括号的深度,并且想知道这是否可以使用 reduce 以相同的方法完成。

我不知道为什么这个问题的补充让我如此困惑,但我想学习。

问题

我一直试图弄清楚它一段时间,这可能是我缺乏对reduce如何工作的理解。

这使用reduce返回true的false,关于括号或均匀地打开和关闭。

function balanceParens(string) {
return !string.split("").reduce((counter, char) => {
// Handle if parens open and close out of order
if (counter < 0) { return counter; }
// Add 1 for each open in order
if (char === "(") { return ++counter; }
// subtract 1 for each close in order
if (char === ")") { return --counter; }
// handle use case if char is not a paren
return counter;
}, 0);
}
console.log(balanceParens("((()))"));

问题

如何使用减少帮助程序方法返回括号的最大深度。

您可以在减少时保持当前深度和最大深度。

function maxDepth(string) {
return string.split("").reduce(({current, max}, char) => {
// Handle if parens open and close out of order
if (current < 0) return {current, max}
// Add 1 for each open in order
if (char === "(") return { current: current + 1, max: Math.max(max, current + 1)}
// subtract 1 for each close in order
if (char === ")") return { current: current - 1, max}
return {current, max}
}, {current: 0, max: 0}).max;
}
console.log(maxDepth("(((()))(((())))()(((((()))))))"));

这是一个紧凑的版本,当括号不平衡时返回NaN。它以函数式风格使用嵌套函数:

function maxDepth(string) {
return ( ([depth, max]) => depth ? NaN : max )
([...string].reduce(([depth, max], ch) => 
(newDepth => [newDepth, newDepth < 0 ? NaN : Math.max(max, newDepth)])
(depth + (ch === "(") - (ch === ")"))
, [0, 0]));
}
console.log(maxDepth("(((()))(((())))()(((((()))))))"));

这应该回答它!

function balanceParens(string) {
let max = 0;
let res = string.split("").reduce((counter, char) => {
// Handle if parens open and close out of order
if (counter < 0) { 
return counter;
}
// Add 1 for each open in order
if (char === "(") {
if(++counter > max) {
max = counter;
}
return counter;
}
// subtract 1 for each close in order
if (char === ")") {
return --counter;
}
// handle use case if char is not a paren
return counter;
}, 0);
console.log("Max depth was :", max);
return !res;
}
console.log(balanceParens("((()(((())))))((((()))))"));

最新更新