/
array.ts
57 lines (44 loc) · 1.75 KB
/
array.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import util from 'util';
import pretty from 'pretty-format';
import {Global} from '@jest/types';
import {EachTests} from '../bind';
const SUPPORTED_PLACEHOLDERS = /%[sdifjoOp%]/g;
const PRETTY_PLACEHOLDER = '%p';
const INDEX_PLACEHOLDER = '%#';
export default (title: string, arrayTable: Global.ArrayTable): EachTests =>
normaliseTable(arrayTable).map((row, index) => ({
arguments: row,
title: formatTitle(title, row, index),
}));
const normaliseTable = (table: Global.ArrayTable): Global.Table =>
isTable(table)
? (table as Global.Table)
: (table as Global.Row).map(colToRow);
const isTable = (table: Global.ArrayTable): boolean =>
table.every(Array.isArray);
const colToRow = (col: Global.Col): Global.Row => [col];
const formatTitle = (
title: string,
row: Global.Row,
rowIndex: number,
): string =>
row.reduce<string>((formattedTitle, value) => {
const [placeholder] = getMatchingPlaceholders(formattedTitle);
if (!placeholder) return formattedTitle;
if (placeholder === PRETTY_PLACEHOLDER)
return interpolatePrettyPlaceholder(formattedTitle, value);
return util.format(formattedTitle, value);
}, interpolateTitleIndex(title, rowIndex));
const getMatchingPlaceholders = (title: string) =>
title.match(SUPPORTED_PLACEHOLDERS) || [];
const interpolateTitleIndex = (title: string, index: number) =>
title.replace(INDEX_PLACEHOLDER, index.toString());
const interpolatePrettyPlaceholder = (title: string, value: unknown) =>
title.replace(PRETTY_PLACEHOLDER, pretty(value, {maxDepth: 1, min: true}));