forked from davidflanagan/jstdg7
-
Notifications
You must be signed in to change notification settings - Fork 0
/
words.js
21 lines (20 loc) · 982 Bytes
/
words.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function words(s) {
var r = /\s+|$/g; // Match one or more spaces or end
r.lastIndex = s.match(/[^ ]/).index; // Start matching at first nonspace
return { // Return an iterable iterator object
[Symbol.iterator]() { // This makes us iterable
return this;
},
next() { // This makes us an iterator
let start = r.lastIndex; // Resume where the last match ended
if (start < s.length) { // If we're not done
let match = r.exec(s); // Match the next word boundary
if (match) { // If we found one, return the word
return { value: s.substring(start, match.index) };
}
}
return { done: true }; // Otherwise, say that we're done
}
};
}
[...words(" abc def ghi! ")] // => ["abc", "def", "ghi!"]