Skip to content

Instantly share code, notes, and snippets.

@oskarbraten
Last active March 23, 2018 23:29
Show Gist options
  • Save oskarbraten/192b8b3df4acb0191bd46f38254440c3 to your computer and use it in GitHub Desktop.
Save oskarbraten/192b8b3df4acb0191bd46f38254440c3 to your computer and use it in GitHub Desktop.
Kotlin inspired built in functions for Javascript
Object.defineProperty(
Object.prototype,
'let',
{
value: function (callback) {
return callback(this);
},
enumerable: false,
writable: false
}
);
Object.defineProperty(
Object.prototype,
'also',
{
value: function (callback) {
callback(this);
return this;
}
}
);
// Emulating Kotlin's run is no problem with a regular function,
// but with an arrow function binding the context is not possible.
// As a fallback we reconstruct a normal function from the arrow functions source code.
// In Chrome the performance penalty is surprisingly little, but in Firefox we're talking one tenth the performance.
Object.defineProperty(
Object.prototype,
'run',
{
value: function (callback) {
if (callback.prototype !== undefined) {
// regular (or native) function
return callback.apply(this);
} else {
// get source, extract body, and reconstruct a regular function
const source = callback.toString();
const body = getArrowFunctionBody(source);
let func = new Function((source.includes(') => {') ? '' : 'return ') + body);
return func.call(this);
}
},
enumerable: false,
writable: false
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment