668 B
668 B
title, type, language, tags, cover, author, dateModified
| title | type | language | tags | cover | author | dateModified | ||
|---|---|---|---|---|---|---|---|---|
| Left substring generator | snippet | javascript |
|
boutique-home-office-1 | chalarangelo | 2022-07-24T05:00:00-04:00 |
Generates all left substrings of a given string.
- Use
String.prototype.lengthto terminate early if the string is empty. - Use a
for...inloop andString.prototype.slice()toyieldeach substring of the given string, starting at the beginning.
const leftSubstrGenerator = function* (str) {
if (!str.length) return;
for (let i in str) yield str.slice(0, i + 1);
};
[...leftSubstrGenerator('hello')];
// [ 'h', 'he', 'hel', 'hell', 'hello' ]