-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Description
There is an TS/ES.next idiom for the JS arguments
array: (...args: any[])
. But using it may produce suboptimal transpilation result, for example:
function debug(...args: any[]) {
if (!settings.debug) return;
console.log("DEBUG:", ...args);
}
produces following JavaScript (ES5) code:
function debug() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!settings.debug)
return;
console.log.apply(console, ["DEBUG:"].concat(args));
}
Note that the arguments
is copied to the args
array immediately at the beginning of the function, before its real usage. This causes the code executed every time the debug()
function is called, even if it is unnecessary.
Expected behavior would be something more intelligent: either moving the arguments
unrolling code closer to the usage place (may be tricky if there are multiple usage points), or using Array.prototype.slice.call(arguments)
in-place without copying it into the temporary args
.
Compare with Babel's transpilation result:
function debug() {
var _console;
if (!settings.debug) return;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
(_console = console).log.apply(_console, ["DEBUG"].concat(args));
}
Note that here the copying was moved past the conditional expression and happens only when needed.