Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active April 8, 2018 01:32
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rauschma/7599488 to your computer and use it in GitHub Desktop.
Save rauschma/7599488 to your computer and use it in GitHub Desktop.
/**
* 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 ]
*/
@Cycymomo
Copy link

In order to init an Array "with n elements" , I usually use (to ensure no hole inside) :

Array.apply(null, Array(3)); // => Array(undefined, undefined, undefined)
Array.apply(null, Array(3)).map(function() {return 'x'}); // => ["x", "x", "x"]
Array.apply(null, Array(3)).map(function(x, i) {return i}); // => [0, 1, 2]

Btw, as far as I remember, I saw this trick on 2ality :)

So, what about this solution ?

function initArray(len, initFunc) {
  if (typeof initFunc !== 'function') {
    // Yes, the return is uncessary, but more descriptive
    initFunc = function () { return undefined };
  }
  return Array.apply(null, Array(len)).map(initFunc);
}

console.log(initArray(3)); // [undefined, undefined, undefined]
console.log(initArray(3, function(x,i) {return i;})); // [0, 1, 2] 
console.log(initArray(3, function() { return 'whatever';})); // ["whatever", "whatever", "whatever"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment