Last active
April 8, 2018 01:32
-
-
Save rauschma/7599488 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Create an array with `len` elements. | |
* | |
* @param [initFunc] Optional: a function that returns | |
* the elements with which to fill the array. | |
* If the function is omitted, all elements are `undefined`. | |
* `initFunc` receives a single parameter: the index of an element. | |
*/ | |
function initArray(len, initFunc) { | |
if (typeof initFunc !== 'function') { | |
// Yes, the return is uncessary, but more descriptive | |
initFunc = function () { return undefined }; | |
} | |
var result = new Array(len); | |
for (var i=0; i < len; i++) { | |
result[i] = initFunc(i); | |
} | |
return result; | |
} | |
/* Interaction: | |
> initArray(3) | |
[ undefined, undefined, undefined ] | |
> initArray(3, function (x) { return x }) | |
[ 0, 1, 2 ] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In order to init an Array "with n elements" , I usually use (to ensure no hole inside) :
Btw, as far as I remember, I saw this trick on 2ality :)
So, what about this solution ?