In my last post, we used ES2015 generators to make a never-ending stream of zombies. A stream is great, but sometimes you need an array. My original approach for making an array of zombies wasn’t elegant, but comments on that post from Ege and Alan showed me a better way using another ES2015 feature.

[more]

Using Array.from

The Array.from function is new in ES2015. It allows you to turn an array-like object into an array. What do I mean by array-like? Basically any object that has a length property will work. That means we can do things like this:

const newArray = Array.from({length:100});
//newArray is now an array with 100 undefined elements!

Array.from also allows you to specify a map callback that’s used when building up the target array. Using that, we can reduce our zombie-creating code down from this…

const herd = [];

const desiredSize = 10000;

while (herd.length < 10000) {
    herd.push(horde.next().value);
}

to this:

const herd = Array.from({length:10000}, () => horde.next().value);

Putting it all together, we now have:

//main.js
const ZombieFactory = require('./ZombieFactory');

const factory = new ZombieFactory();

const horde = factory.getHorde();

const herd = Array.from({length:10000}, () => horde.next().value);

console.log('Now we have a *lot* of zombies...');

for (let i=0; i < herd.length; i++) {
    console.log(herd[i].sayHi());
}

Much cleaner!