Skip to content

Instantly share code, notes, and snippets.

@paceaux
Last active December 30, 2019 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paceaux/a4dee9accd1319f876c242157d63c645 to your computer and use it in GitHub Desktop.
Save paceaux/a4dee9accd1319f876c242157d63c645 to your computer and use it in GitHub Desktop.
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