2

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!

MrJs0n
  • 95
  • 2
  • 4
  • Not sure what you want to achieve. The function in your example is pure: it doesn't have a state, nor returns different values when receiving the same arguments. Your usage example showed exactly how a pure function should behave. You expected that a prior call would affect the result of a subsequent call? – Thiago Barcala Jan 20 '18 at 17:44
  • Thanks. Maybe i'm a little confused about pure and impure function, though. The goal is to solve a coding interview question... So, i'm not crazy :) I thought that a function that maintain an internal state isn't pure, right? And that "gooloooz" is wrong. – MrJs0n Jan 20 '18 at 17:51

1 Answers1

0

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);
}
Thiago Barcala
  • 6,463
  • 2
  • 20
  • 23