functional programming - Is it possible to rewrite JavaScript's apply function? -
i've been rewriting lot of javascript's higher-order functions hang of functional programming, , i'm stuck on apply
. possible write apply
in javascript? assuming other native functions present, , es5 spec being used.
with es5 , below, don't think can without using eval
(see below). can almost massive switch statment on args.length
, @ point, have there's limit number of cases
in switch
.
function.prototype.newapply = function(thisarg, args) { switch (args.length) { case 0: return this.call(thisarg); case 1: return this.call(thisarg, args[0]); case 2: return this.call(thisarg, args[0], args[1]); // etc.. default: throw new error("she canna tek more!"); } };
if you're allowing eval
, though, can absolutely it — full credit blex suggesting eval
:
function.prototype.newapply = function(thisarg, args) { var f = this, call = "f.call(thisarg", i; (i = 1; < args.length; ++i) { call += ", args[" + + "]"; } call += ")"; return eval(call); };
live example:
function.prototype.newapply = function(thisarg, args) { var f = this, call = "f.call(thisarg", i; (i = 0; < args.length; ++i) { call += ", args[" + + "]"; } call += ")"; return eval(call); }; var obj1 = { foo: "foo", bar: "bar" }; var obj2 = { foo: "f", bar: "b" }; function caps(o1, o2) { var k; snippet.log("this.x = " + this.x); (k in o1) { o1[k] = o1[k].touppercase(); } (k in o2) { o2[k] = o2[k].tolowercase(); } } caps.newapply({x:42}, [obj1, obj2]); snippet.log(json.stringify(obj1)); snippet.log(json.stringify(obj2));
<!-- script provides `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
or if want use array#reduce
:
function.prototype.newapply = function(thisarg, args) { var f = this, call = args.reduce(function(acc, _, index) { return acc + ", args[" + index + "]"; }, "f.call(thisarg") + ")"; return eval(call); };
you said es5 in question, completeness: it's easy in es6 spread operator (...
):
function.prototype.newapply = function(thisarg, args) { return this.call(thisarg, ...args); };
Comments
Post a Comment