Skip to content

Instantly share code, notes, and snippets.

@drench
Created March 10, 2024 13:41
Show Gist options
  • Select an option

  • Save drench/da632023508d5ba6624f91bf605648c2 to your computer and use it in GitHub Desktop.

Select an option

Save drench/da632023508d5ba6624f91bf605648c2 to your computer and use it in GitHub Desktop.

Revisions

  1. drench created this gist Mar 10, 2024.
    58 changes: 58 additions & 0 deletions string-succ.test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    // 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);
    });