try-catch-FAIL

Failure is inevitable

NAVIGATION - SEARCH

A More Elegant Zombie Horde Using Array.from

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.

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!

About Matt Honeycutt...

Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications. He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.

He's also an author for Pluralsight, where he publishes courses on everything from web applications to testing!

blog comments powered by Disqus