Last active
August 28, 2015 16:25
-
-
Save michaelficarra/8b821fe7df904ec49c1f to your computer and use it in GitHub Desktop.
creating a function with a given name and arity in ES5 vs. ES2015
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var apply = Function.prototype.call.bind(Function.prototype.apply); | |
function createFunctionES5(name, arity, behaviour) { | |
var params = Array.apply(null, Array(arity)).map(function (x, p) { return "p" + p; }).join(","); | |
var code = "return function " + name + "(" + params + ") { return apply(f, this, arguments); }"; | |
return Function("apply", "f", code)(apply, behaviour); | |
} | |
var define = Object.defineProperty.bind(Object); | |
function createFunctionES2015(name, arity, behaviour) { | |
function f(){ return apply(behaviour, this, arguments); }; | |
define(f, "name", { value: name, writable: false, enumerable: false, configurable: true }); | |
define(f, "length", { value: arity, writable: false, enumerable: false, configurable: true }); | |
return f; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh neat! Should help with currying