Search code examples
javascriptstatelesspure-function

Multiple inline pure function calls using JavaScript...?


I'm scratching my head about solving a problem within JS and pure functions. The one below is an example of impure function but useful to understand what it does.

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'

What if I need to make it pure to avoid any side effect? In the following example, the issue of an impure function shows up.

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

Thanks!


Solution

  • Now I got you! :D

    fn is pure, but the function returned by it is not.

    You can get your intended behaviour with this approach:

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