Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions kata/5 kyu/string-incrementer/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import incrementString from '.';

describe('incrementString', () => {
it('should increment number in string', () => {
expect.assertions(6);

expect(incrementString('foobar000')).toBe('foobar001');
expect(incrementString('foo')).toBe('foo1');
expect(incrementString('foobar001')).toBe('foobar002');
expect(incrementString('foobar99')).toBe('foobar100');
expect(incrementString('foobar099')).toBe('foobar100');
expect(incrementString('')).toBe('1');
});
});
16 changes: 16 additions & 0 deletions kata/5 kyu/string-incrementer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function incrementString(strng: string): string {
const { groups } = strng.match(/(?<string>[a-zA-Z]+)?(?<number>\d+)?/) || [];

if (!groups) {
throw new Error('Invalid input');
}

const { string = '', number = '0' } = groups;

const numberLength = number.length;
const parsedNumber = parseInt(number, 10);

return string + (parsedNumber + 1).toString().padStart(numberLength, '0');
}

export default incrementString;
35 changes: 35 additions & 0 deletions kata/5 kyu/string-incrementer/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# [String incrementer](https://www.codewars.com/kata/54a91a4883a7de5d7800009c)

Your job is to write a function which increments a string, to create a new string.

- If the string already ends with a number, the number should be incremented by 1.
- If the string does not end with a number. the number 1 should be appended to the new string.

Examples:

`foo -> foo1`

`foobar23 -> foobar24`

`foo0042 -> foo0043`

`foo9 -> foo10`

`foo099 -> foo100`

_Attention: If the number has leading zeros the amount of digits should be considered._

---

## Tags

- Advanced Language Features
- Algorithms
- Data Types
- Declarative Programming
- Fundamentals
- Logic
- Parsing
- Programming Paradigms
- Regular Expressions
- Strings