DEV Community

Iven Marquardt
Iven Marquardt

Posted on

Lil' functional auxiliary helpers: `thisify`

If you want a self-referencing object in an ad-hoc manner you should meet thisify:

const thisify = f => f({});

const comp = f => g => x => f(g(x));
const log = prefix => x => (console.log(prefix, x), x);
const sqr = x => x * x;

const foo = thisify(o => {
  o.bar = 5;

  o.once = op => {
    const memo = op(o.bar);
    o.once = _ => memo;
    return memo;
  }

  return o;
});

foo.once(comp(log("logs")) (sqr)); // logs 25 + yields 25
foo.once(comp(log("logs")) (sqr)); // yields 25

run code

f => f({}) is all it takes to mimic Javascript's this.

Discussion (0)