jskatas.org Continuously Learn JavaScript. Your Way.

Iterator: protocol

A simple iterable without items inside, implementing the right protocol

the iteratorFunction needs to comply to the iterator protocol

must return an object
function iteratorFunction() {} assert.equal(typeof iteratorFunction(), 'object');
the object must have a function assigned to a key next
function iteratorFunction() { return {next: () => ({done: true})}; } assert.equal(typeof iteratorFunction().next, 'function');
calling next() must return an object with {done: true}
function iteratorFunction() { return {next: () => ({done: true})}; } assert.deepEqual(iteratorFunction().next(), {done: true});

the iterable

must be an object
function iteratorFunction() { return {next: () => ({done: true})}; } const iterable = {[Symbol.iterator]: iteratorFunction}; assert.equal(typeof iterable, 'object');
must have the iterator function assigned to the key Symbol.iterator
function iteratorFunction() { return {next: () => ({done: true})}; } const iterable = {[Symbol.iterator]: iteratorFunction}; assert.equal(iterable[Symbol.iterator], iteratorFunction);

using the iterable

it contains no values
function iteratorFunction() { return {next: () => ({done: true})}; } const iterable = {[Symbol.iterator]: iteratorFunction}; let values; for (let value of iterable) { values += value; } assert.equal(values, '');
has no .length property
function iteratorFunction() { return {next: () => ({done: true})}; } const iterable = {[Symbol.iterator]: iteratorFunction}; const hasLengthProperty = iterable; assert.equal(hasLengthProperty, false);

can be converted to an array

using Array.from()
function iteratorFunction() { return {next: () => ({done: true})}; } const iterable = {[Symbol.iterator]: iteratorFunction}; const arr = iterable; assert.equal(Array.isArray(arr), true);
where .length is still 0
function iteratorFunction() { return {next: () => ({done: true})}; } const iterable = {[Symbol.iterator]: iteratorFunction}; const arr = iterable; const length = arr.length; assert.equal(length, 0);

Related Katas

Iterator

Difficulty Level

EXPERT

First Published

12 May 2015

Stats

9 tests to solve