Iterator Example

Share

Iterator Example

This is a poor example as you could certainly accomplish this more easily with .map(), however, this demonstrates that the iterator ‘remembers’ its position and picks up where it left off. A better example would be where other procedures or logic are executed between calls.

function makeIterator(array) {
    var nextIndex = 0;
    return {
        next: ()=>(nextIndex < array.length) && array[nextIndex++],
        remain: ()=>array.length - nextIndex
    }
}
var fun = makeIterator(['fe', 'fi', 'fo', 'fum', 'I', 'smell']);

while(fun.remain()){
    console.log(fun.next());
}
Share

Array Iteration

Share

Two quick ways to iterate through an array (from .length to 0).

What’s the point?

  • It’s fast to compare something to zero
  • Less code overall

Why it’s weird…

We’re used to counting from zero to length – not vice-versa

When not to use

The only place I can think of that this wouldn’t be a good idea would be when you need to iterate over the array in ascending key order.

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var b = a.length;

// quickly iterate through array
while (b--) {
    console.log(a[b]);
}

// declaring var in same line
for (var c = a.length; c--; ) {
    console.log(a[c]);
}

// of course THIS is best
a.forEach(i => console.log(i));
Share

Thoughts on coercion

Share

Thoughts on coercion

Here’s an interesting tidbit. If you’ve ever used indexOf to determine if a string contains another string (perhaps I could word this better…), then you’ve probably used something like:

var a = 'Jim';
a.indexOf('i') !== -1; // true

As you’re probably aware, if the string is not found, –1 is the return value.

A simpler and more efficient way to accomplish this test is:

var a = 'Jim';
~a.indexOf('i'); // true (coerced)

or

Boolean(~a.indexOf('i')); // true

A lot of people will state that coercion in JS is evil. I’d state that what is really evil is when people don’t know what that coercion is doing. I recently watched a video series by Kyle Simpson where he illustrated a few places where using coercion to your advantage will create simpler, easier to understand, less error-prone code. For example:

var foo; // undefined

Let’s say that foo, in this case could be undefined or null.
Using explicit coercion, our check for this value would be:

if ( foo===undefined || foo===null ) {
    // should work, all bases are covered
}

A simpler, more readable check:

if ( foo == null ) {
    // works for null or undefined
}
Share