Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom Iterators
/** 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];
}
}
}
}
/** 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
You can’t perform that action at this time.