5 ms·
The only solution I could think of is this: function foo(n) { var result = []; for (var i = 0; i < n; i++) (function(j) { resul
by bbotond 12y ago
The only solution I could think of is this:
function foo(n) {
var result = [];
for (var i = 0; i < n; i++)
(function(j) { result.push(function() { return j; }); })(i);
return result;
}
What are the two others?
- serve_yay 12y agoThat's using a closure, another would be to use Function.prototype.bind (but really that's still using a closure, just putting it out of sight), can't think of any others.
- jnbiche 12y ago>Function.prototype.bind (but really that's still using a closure, just putting it out of sight), How is `bind` still using a closure? `bind` just allows users to alter a function's execution context. However, the implementation varies according to the JS engine. Some of them may use a closure internally as a part of the process, but I don't think V8 does.
- serve_yay 12y agoSure, I was cheating there a little bit. I was thinking in terms of how one would actually implement bind in user land JS code, which would use a closure. V8's implementation of bind likely does not.
- Daiz 12y agoYou could use Function.prototype.bind in a couple ways, or even Array.prototype.map (though sadly you can't really do new Array(n).map, if that was true you could make this a one-liner). // new Array(n) could just be [] in all examples // // using Array.prototype.map // sadly you can't do new Array(n).map // because it doesn't iterate over undefined functions function foo(n) { for (var ret = new Array(n), i = 0; i < n; ++i) { ret[i] = i; } return ret.map(function(_,n) { return function() { return n; }; }); } // using Function.prototype.bind in a couple ways function foo(n) { function num() { return +this; } for (var ret = new Array(n), i = 0; i < n; ++i) { ret[i] = num.bind(i); } return ret; } function foo(n) { function num(a) { return a; } for (var ret = new Array(n), i = 0; i < n; ++i) { ret[i] = num.bind(null, i); // could bind this to pretty much whatever here } return ret; }
- Soldier-B 12y agofunction foo(a){ return Array.apply(0, new Array(a)).map(function(_, b){ return Number.bind(null, b) }); }
- mendelk 12y agoIf you're into one-liners, CoffeeScript is your friend :) foo = (n) -> (-> i) for i in [0..n]
- rmrfrmrf 12y agoClose, but I checked it and the value of `i` won't bind to the function. You also have to use `...` (exclusive range) instead of `..` to prevent an off-by-one error. Here's one way: foo = (n) -> ((a) -> a).bind(null, i) for i in [0...n] Here's a more esoteric/bad style (but cute) way: foo = (n) -> (-> +@).bind i for i in [0...n]
- alxndr 12y agoI've been preferring explicit `map()`s in my CoffeeScript for exactly that reason.