Last active
August 29, 2015 14:15
-
-
Save raganwald/967f99d90738896cfa06 to your computer and use it in GitHub Desktop.
ES-6 Gotchas
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
const arrayIterator = (array) => { | |
let i = 0; | |
return () => { | |
const done = i < array.length; | |
return { | |
done, | |
value: done ? undefined : array[i++] | |
} | |
} | |
} | |
const brokenIteratorSum = (iterator) => { | |
let done, value, | |
sum = 0;; | |
while (({done, value} = iterator(), !done)) { | |
sum += value | |
} | |
return sum | |
} | |
brokenIteratorSum(arrayIterator([1, 4, 9, 16, 25])) | |
//=> repl: cannot add a declaration here in node type WhileStatement | |
const iteratorSum = (iterator) => { | |
let i, | |
sum = 0;; | |
while ((i = iterator(), !i.done)) { | |
sum += i.value; | |
} | |
return sum | |
} | |
iteratorSum(arrayIterator([1, 4, 9, 16, 25])) | |
//=> 55 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a journey... Into sound.