Skip to content

Commit

Permalink
test: add tests for splitString
Browse files Browse the repository at this point in the history
  • Loading branch information
motss committed Sep 18, 2021
1 parent bf371e6 commit c7ee8f9
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 13 deletions.
24 changes: 11 additions & 13 deletions src/helpers/split-string.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
type SplitStringCallbackFn<ReturnType> = (
element: ReturnType,
element: string,
index: number,
array: ReturnType[]
array: string[]
) => ReturnType;

export type splitString = {
(source: string): string[];
<ReturnType>(source: string, callbackFn: SplitStringCallbackFn<ReturnType>): ReturnType[];
}

export function splitString<SourceType extends string = string, ReturnType = string>(
source: SourceType,
callbackFn?: SplitStringCallbackFn<ReturnType>,
export function splitString<ReturnType = string>(
source: string,
splitFunction?: SplitStringCallbackFn<ReturnType>,
separator: RegExp | string = /,\s*/
): ReturnType[] {
const dateList = typeof source === 'string' && source.length > 0
? source.split(separator) as unknown as ReturnType[]
? source.split(separator)
: [];

if (!dateList.length) return [];
if (callbackFn == null) return dateList;
if (splitFunction == null) return dateList as unknown as ReturnType[];

return dateList.map(callbackFn);
return dateList.map(
(n, i, arr) =>
splitFunction(n, i, arr)
);
}
53 changes: 53 additions & 0 deletions src/tests/helpers/split-string.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { expect } from '@open-wc/testing';

import { splitString } from '../../helpers/split-string';
import { messageFormatter } from '../test-utils/message-formatter';

describe(splitString.name, () => {
const str = 'hello, world, everyone';
const expected = str.split(/,\s*/);

type A = [string, string[]];

const cases: A[] = [
['', []],
[str, expected],
];

cases.forEach((a) => {
it(
messageFormatter('splits string (%s)', a),
() => {
const [testSource, expected] = a;
const result = splitString(testSource);

expect(result).deep.equal(expected);
}
);
});

type A1 = [RegExp?];

const cases1: A1[] = [
[],
[/,\s/],
];

cases1.forEach((a) => {
it(
messageFormatter('splits string with optional callback and optional separator (%s)', a),
() => {
const [testSeparator] = a;

const result = splitString<[string]>(
str,
(n) => [n],
testSeparator
);

expect(result).deep.equal(expected.map(n => [n]));
}
);
});

});

0 comments on commit c7ee8f9

Please sign in to comment.