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}, ...subs) => (...args) => {
const buf = [],
table = {}
function addVar(name, value) {
table[name] = value
return name
}
for (let i = 0; i < raw.length; i++) {
buf.push(raw[i].replace(/#(\d+)/g, (_, n) => addVar('___' + n, args[n])))
if (i < raw.length - 1)
buf.push(addVar('____' + i, subs[i]))
}
const expr = buf.join('')
const keys = Object.keys(table)
const values = keys.map(k => table[k])
return (new (Function.prototype.bind.apply(Function, [null, keys, `return ${expr}`]))).apply(null, values)
}
/*
> λ`(#0 + #1) * #2`(4, 2, 7)
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