Skip to content

Instantly share code, notes, and snippets.

@drench
Created March 10, 2024 13:41
Show Gist options
  • Save drench/da632023508d5ba6624f91bf605648c2 to your computer and use it in GitHub Desktop.
Save drench/da632023508d5ba6624f91bf605648c2 to your computer and use it in GitHub Desktop.
A generator that works something like Ruby's `String#succ` (for lowercase strings only)
// Run with jest
const succ = function * (string) {
const matchResult = string.match(/^([a-z]*)([a-z])$/);
if (matchResult) {
const prefix = matchResult[1];
const last_char = matchResult[2];
if (last_char == 'z') {
yield arguments.callee(prefix).next().value + 'a';
}
else {
yield (prefix + String.fromCharCode(last_char.charCodeAt(0) + 1));
}
} else {
if (string.match(/^[a-z]*$/)) {
yield 'a';
}
else {
throw new TypeError('String must include only lowercase letters, or be empty');
}
}
}
test('', () => {
const subject = succ('');
expect(subject.next().value).toEqual('a');
});
test('a', () => {
const subject = succ('a');
expect(subject.next().value).toEqual('b');
});
test('z', () => {
const subject = succ('z');
expect(subject.next().value).toEqual('aa');
});
test('aa', () => {
const subject = succ('aa');
expect(subject.next().value).toEqual('ab');
});
test('az', () => {
const subject = succ('az');
expect(subject.next().value).toEqual('ba');
});
test('zz', () => {
const subject = succ('zz');
expect(subject.next().value).toEqual('aaa');
});
test('WHAT', () => {
const subject = succ('WHAT');
expect(() => subject.next()).toThrow(TypeError);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment