Last active
July 5, 2018 19:10
-
-
Save abstractmachines/1c72a2bb4dee5b09abebee76fa77c0e0 to your computer and use it in GitHub Desktop.
JavaScript Iterators : Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* JavaScript Iterators | |
An Iterator Object is a data structure that has a .next() method that can be called repeatedly. | |
Iterators use the Well Known Symbol called Symbol.iterator. | |
(The Iterable Object has an Iterator pointer for indexing.) | |
The Iterator object has two properties, value and done (boolean). Iteration will continue so | |
long as done is falsey. Once done is truthy, iteration stops. | |
Just like C++ iterators for C++ data structures, JavaScript iterators iterate through an entire | |
collection, and if incremented once more, will go "one value beyond" the collection to return | |
null pointer (or, in JS, undefined). The way this is done in JS is to call the .next() function | |
once more. | |
Sources: | |
1 - Axel Rauschmeyer: http://exploringjs.com/es6/ch_iteration.html | |
2 - http://www.zsoltnagy.eu/es6-iterators-and-generators-in-practice/ | |
*/ | |
const arr = [ 'a', 'b', 'c'] | |
const it = arr[Symbol.iterator]() | |
console.log(it.next()) | |
// { value: "a", done: false } | |
console.log(it.next()) | |
// { value: "b", done: false } | |
console.log(it.next()) | |
// { value: "c", done: false } | |
console.log(it.next()) | |
// { value: undefined, done: true } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Arrays are just built-in iterables in JS
Converting other things to arrays
Array.from()
Spread operator can convert Sets to Arrays
The spread operator inserts the values of an iterable into an Array (from Dr Axel):
JS Array Methods are awesome
Don't forget to use JS array methods like
.includes()
,.some()
,.every()
, and more.