Skip to content

Instantly share code, notes, and snippets.

@pelotom
Last active December 30, 2020 11:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pelotom/98e0de19adfc164f9248 to your computer and use it in GitHub Desktop.
Save pelotom/98e0de19adfc164f9248 to your computer and use it in GitHub Desktop.
const λ = ({raw}, ...subs) => {
const expr = raw
.reduce((prev, next, n) => prev + `(___subs[${n - 1}])` + next)
.replace(/#(\d+)/g, (_, n) => `(___args[${n}])`)
const evaluate = new Function('___subs', '___args', `return (${expr});`)
return (...args) => evaluate(subs, args)
}
/*
> λ`(#0 + #2) * #1`(4, 7, 2)
42
> [{x: 'foo'}, {x: true}, {x: 3}].map(λ`#0.x`)
["foo", true, 3]
> const field = 'x', n = 4
> [{x: 8}, {x: 3}, {x: 9}].map(λ`#0[${field}] * (#1 + ${n})`)
[32,15,54]
*/
@nitsanavni
Copy link

can we make this safer by making it type-safe with typescript?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment