【问题标题】:Multiple inline pure function calls using JavaScript...?使用 JavaScript 的多个内联纯函数调用...?
【发布时间】:2018-06-29 18:00:16
【问题描述】:

我正在为解决 JS 和纯函数中的问题而摸不着头脑。下面是一个不纯函数的示例,但有助于理解它的作用。

function fn(some) {
    var ret = 'g',
        mid = 'o';

    if (some) return ret + some;
    ret += mid;

    return function d(thing) {
        if (thing) return ret += thing;
        ret += mid;
        return d;
    }
}

// Some output examples
fn('l')                 => 'gl'
fn()('l')               => 'gol'
fn()()()()()()()()('l') => 'gooooooool'

如果我需要使其纯净以避免任何副作用怎么办?在以下示例中,出现了不纯函数的问题。

var state = fn()(); 
state('l')       => 'gool'
state()()()('z') => 'goooooz' // ...and not 'gooloooz'

谢谢!

【问题讨论】:

  • 不确定您想要实现什么。您示例中的函数是纯函数:它没有状态,也没有在接收相同参数时返回不同的值。您的使用示例准确地显示了纯函数的行为方式。您预计之前的调用会影响后续调用的结果吗?
  • 谢谢。不过,也许我对纯函数和不纯函数有点困惑。目标是解决编码面试问题......所以,我没有疯:) 我认为保持内部状态的函数不是纯粹的,对吧?而那个“gooloooz”是错误的。

标签: javascript stateless pure-function


【解决方案1】:

现在我找到你了! :D

fn是纯的,但它返回的函数不是。

您可以通过这种方法获得预期的行为:

function accumulate (accumulator) {
    return function (value) {
        return value ? accumulator + value : accumulate(accumulator + 'o');
    };
}

function fn(some) {
    return accumulate('g')(some);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多