Created
June 18, 2015 23:58
-
-
Save isRuslan/c4c39a4a18016de77a5f to your computer and use it in GitHub Desktop.
JS ES6: Iterable | Iterators. Play in repl: http://bit.ly/1GvjFg7
This file contains hidden or 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
| /* | |
| Iterators | Iterables: | |
| Iterable (data structure): Iterator (obj that enumirates data): | |
| [Symbol.iterator]() ---> .next() | |
| `for of` interate only on Iterables | |
| */ | |
| // array | |
| for (let a of [1, ...[2, 3, 4], 'foo']) { | |
| console.log(a); | |
| } | |
| console.log(); | |
| // string | |
| for (let x of '\u2744\u274E') { | |
| console.log(x); | |
| } | |
| console.log(); | |
| // Map: [key, value] pair + destructuring | |
| let map = new Map().set('foo', 1).set('bar', [1, 2, 3]); | |
| for (let [k, v] of map) { | |
| console.log(`key = ${k}, value = ${v}`) | |
| } | |
| console.log(); | |
| // Set: sequance | |
| let set = new Set().add('foo').add(123); | |
| for (let s of set) { | |
| console.log(s) | |
| } | |
| console.log(); | |
| // arguments... | |
| // DOM | |
| for (let node of document.querySelectorAll('a')) { | |
| console.log(node) | |
| } | |
| /* | |
| TASK: create function take(n, iterable), | |
| which returns an iterable over | |
| the first n items of iterable. | |
| */ | |
| function take (n, iterable) { | |
| // do | |
| } | |
| let arr = ['a', 'b', 'c', 'd']; | |
| for (let x of take(2, arr)) { | |
| console.log(x); | |
| } | |
| // Output: | |
| // a | |
| // b | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment