Last active
December 30, 2019 20:01
-
-
Save paceaux/a4dee9accd1319f876c242157d63c645 to your computer and use it in GitHub Desktop.
Custom Iterators
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
/** Creates an array that, when iterated, only returns ruthy items | |
* @param {array} iterable | |
* | |
* @example const mixedBag = new TruthyArray(1, 0, 'foo', '', true, false, undefined, null, 'three']) | |
* for (item of mixedBag) { | |
* console.log(item); | |
* } | |
* | |
*/ | |
class TruthyArray extends Array { | |
constructor(value) { | |
super(...value); | |
this.value = [...value]; | |
} | |
get [Symbol.species]() { | |
return Array; | |
} | |
*[Symbol.iterator]() { | |
let itemIndex = -1; | |
while (itemIndex < this.value.length ) { | |
if (this.value[++itemIndex]) { | |
yield this.value[itemIndex]; | |
} | |
} | |
} | |
} |
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
/** returns a string whose iterator will iterate by whole words | |
* @param {string} text | |
*/ | |
function WordString(text) { | |
const string = new String(text); // make explicit object | |
const words = string.split(' '); // split by spaces | |
let wordIndex = 0; | |
string[Symbol.iterator] = function* stringIterator() { | |
while (wordIndex < words.length) { | |
yield words[wordIndex++] | |
.replace(new RegExp('[!.?]', 'g'),''); // remove any punctuation | |
} | |
} | |
return string; | |
} | |
/** returns a string that can be iterated on by sentences | |
* @param {string} text | |
* | |
* @example const sentences = 'This is a sentence. Isn't this one? ¿Y también esta?' | |
* for (sentence of sentences) { | |
* console.log(sentence); | |
* } | |
*/ | |
function SentenceString(text) { | |
const string = new String(text); | |
const sentences = string.split(new RegExp('[!.?]', 'g')); // capture by end punctuation | |
let sentenceIndex = 0; | |
string[Symbol.iterator] = function* SentenceIterator() { | |
while (sentenceIndex < sentences.length) { | |
yield sentences[sentenceIndex++] | |
.replace(new RegExp('[¿¡]', 'g'),'') | |
.trim(); // remove beginning punctuation and trim whitespace | |
} | |
} | |
return string; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment