DEV Community

Iven Marquardt
Iven Marquardt

Posted on

2 1

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
Enter fullscreen mode Exit fullscreen mode

run code

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

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay