使用JavaScript的多个内联纯函数调用......?

时间:2018-01-20 17:19:59

标签: javascript stateless pure-function

我在解决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'

谢谢!

1 个答案:

答案 0 :(得分:0)

现在我找到了你! :d

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

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

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

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