Files
30-seconds-of-code/snippets/js/s/right-substring-generator.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

664 B

title, type, language, tags, cover, author, dateModified
title type language tags cover author dateModified
Right substring generator snippet javascript
string
generator
boutique-home-office-2 chalarangelo 2022-07-25T05:00:00-04:00

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 and String.prototype.slice() to yield 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' ]