Right substring generator
JavaScript, String, Generator · Jul 25, 2022

Generates all right substrings of a given string.
- Use
String.prototype.length
to terminate early if the string is empty. - Use a
for...in
loop andString.prototype.slice()
toyield
each substring of the given string, starting at the end.
const rightSubstrGenerator = function* (str) {
if (!str.length) return;
for (let i in str) yield str.slice(-i - 1);
};
[...rightSubstrGenerator('hello')];
// [ 'o', 'lo', 'llo', 'ello', 'hello' ]
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.