Last active
December 30, 2020 11:18
-
-
Save pelotom/98e0de19adfc164f9248 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can we make this safer by making it type-safe with typescript?