Skip to content

Commit 47bfda5

Browse files
authored
Merge pull request #18 from ryoppippi/feature/17
implement split function
2 parents fea149d + deaf05c commit 47bfda5

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ export * from './capitalize.js';
44
export * from './uncapitalize.js';
55
export * from './lowercase.js';
66
export * from './uppercase.js';
7+
export * from './split.js';

src/split.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// @ts-strict
2+
3+
/**
4+
* @template {Readonly<string>} T
5+
* @template {Readonly<string>} U
6+
* @typedef {import('type-fest').IsStringLiteral<T> extends true ? import('type-fest').Split<T,U> : string[]} SplitString<T,U>
7+
*/
8+
9+
/**
10+
* @description Split string by separator
11+
*
12+
* @template {Readonly<string>} T
13+
*
14+
* @template {Readonly<string>} U
15+
*
16+
* @param {T} input - string to split. type should be matched to T
17+
*
18+
* @param {U} separator - separator to split string. type should be matched to U
19+
*
20+
* @returns {SplitString<T,U>}
21+
*
22+
* @example
23+
* split('Abc', 'b') // returns ['A', 'c']
24+
*
25+
* @example
26+
* split('a-b-c', '-') // returns ['a', 'b', 'c']
27+
*
28+
* @example
29+
* split('a-b-c', '') // returns ['a', '-', 'b', '-', 'c']
30+
*
31+
* @example
32+
* split('a-b-c', '$') // returns ['a-b-c']
33+
*
34+
*/
35+
export function split(input, separator) {
36+
return /** @type {SplitString<T,U>} */ input.split(separator);
37+
}

src/split.test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { split } from '.';
2+
import { describe, it, expect } from 'vitest';
3+
describe('split', () => {
4+
it('should split a string into an array', () => {
5+
const before = 'abc' as const;
6+
const splitted = split(before, '');
7+
const expected = ['a', 'b', 'c'] satisfies typeof splitted;
8+
expect(splitted).toEqual(expected);
9+
});
10+
it('should split a string into an array', () => {
11+
const before = 'a-b-c' as const;
12+
const splitted = split(before, '-');
13+
const expected = ['a', 'b', 'c'] satisfies typeof splitted;
14+
expect(splitted).toEqual(expected);
15+
});
16+
it('should split a string into an array', () => {
17+
const before = 'a-b-c' as const;
18+
const splitted = split(before, '');
19+
const expected = ['a', '-', 'b', '-', 'c'] satisfies typeof splitted;
20+
expect(splitted).toEqual(expected);
21+
});
22+
it('should not split a string into an array with wrong separator', () => {
23+
const before = 'a-b-c' as const;
24+
const splitted = split(before, '$');
25+
const expected = ['a-b-c'] satisfies typeof splitted;
26+
expect(splitted).toEqual(expected);
27+
});
28+
});

0 commit comments

Comments
 (0)