扩展使用Javascript的array.reduce帮助方法 [英] Expanding use of Javascript array.reduce helper method

查看:212
本文介绍了扩展使用Javascript的array.reduce帮助方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我正在关注Udemy的课程,覆盖所有ES6功能。在其中一个教训中,教练谈论使用减少辅助方法来解决普遍的平衡括号面试问题。

I am following a course on Udemy which goes over all of the ES6 features. In one of the lessons the instructor talks about using the reduce helper method to solve the popular balance parenthesis interview question.

我可以解决这个没有reduce方法。尽管使用reduce方法,它确实以较少的代码完成了这项工作。我被要求在接受采访时找到圆括号的深度,并且想知道是否可以用相同的方法使用reduce来完成。

I can solve this without the reduce method. Although with the reduce method it does get the job done in less code. I have been asked to find the depth of the parenthesis in an interview before and was wondering if this could all be done in the same method using reduce.

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

I do not know why this addition to the question confuses me so much but I would like to learn.

问题

我一直在试图弄清楚一段时间,

I have been trying to figure it out for a while and it might be my lack of understanding how reduce works.

示例

这个如果圆括号或打开和关闭均匀,则使用reduce返回true。

This uses reduce to return true of false regarding if the parenthesis or open and closed evenly.

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("((()))"));

问题

如何使用reduce helpper方法返回括号的最大深度。

How would I return the max depth of the parenthesis using the reduce helper method.

推荐答案

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

You could maintain current depth and max depth while reducing.

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("(((()))(((())))()(((((()))))))"));

这篇关于扩展使用Javascript的array.reduce帮助方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆