by spankalee · 2y ago · 0 comments
I've wanted the ability to reference the callsite in functions, and lobbied the V8 team for something like arguments.callsite, but was (probably rightly) politely told no.
But if you're willing to abuse tagged template literal syntax, they're really just function calls, so you can do something like:
const dumbExample = (x) => {
while (someComplicatedStuffHappens()) {
pretendLikeThisFunctionIsBig();
}
const result = memoize(doSomethingVeryExpensive, x)``;
doMoreInterestingWork();
}
memoize() must return a template tag function, which will be invoked with a TemplateStringsArray (because of the ``) that can act like a callsite identifier, which can be a key into a WeakMap of memoization dictionaries.It's mostly a curiosity because who wants that syntax, but it's interesting that JavaScript does have the special power hidden behind one feature.
[1]: https://gist.github.com/aziis98/c8de74a29d5b1721983501fe28eb...
I don't know precisely but this feels like this would be very useful for something. I'll continue to experiment with this in the future
> This allows the tag to cache the result based on the identity of its first argument. To further ensure the array value's stability, the first argument and its raw property are both frozen, so you can't mutate them in any way.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Tagged template literals are crazy powerful, and it would be really neat to add some of that magic to other language features. If functions could access the callsite, you could implement React hooks without the whole hooks environment. Each hook could just cache it's state off the callsite object.
function lexicalMagic() {
const callHistory = [];
function tag(strings, ...values) {
callHistory.push(strings);
// Return a freshly made object
return {};
}
function evaluateLiteral() {
return tag`Hello, ${"world"}!`;
}
return { evaluateLiteral, callHistory }
}
We can create multiple "instances" of our closures, just as we expect and they do in fact produce distinct everything-else: > const first = lexicalMagic()
> const second = lexicalMagic()
> first.evaluateLiteral === second.evaluateLiteral
false
> first.callHistory === second.callHistory
false
Using them doesn't behave any differently than the unclosured versions (as expected): > first.evaluateLiteral() === first.evaluateLiteral()
false
> first.callHistory[0] === first.callHistory[1]
true
> second.evaluateLiteral() === second.evaluateLiteral()
false
> second.callHistory[0] === second.callHistory[1]
true
However, there is only one instance of the template literal, not two as we might expect. This is really helpful for some cases, but it definitely is surprising given the rest-of-JS: > first.callHistory[0] === second.callHistory[1]
true