Skip to content

Instantly share code, notes, and snippets.

@pelotom
Last active December 30, 2020 11:18
Show Gist options
  • Select an option

  • Save pelotom/98e0de19adfc164f9248 to your computer and use it in GitHub Desktop.

Select an option

Save pelotom/98e0de19adfc164f9248 to your computer and use it in GitHub Desktop.
const λ = ({raw: [raw]}, ...subs) => {
if (subs.length > 0) {
console.error('Interpolation is unnecessary, just use x instead of ${x}')
return
}
const indices = []
const expr = raw.replace(/#(\d+)/g, (_, n) => {
indices.push(n)
return '(vars[' + n + '])'
})
const f = eval('(function (vars) { return (' + expr + '); })')
return (...args) => {
const vars = {}
indices.forEach(i => { vars[i] = args[i] })
return f(vars)
}
}
/*
> λ`(#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
Copy Markdown

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