-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
70 lines (61 loc) · 1.89 KB
/
index.js
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
58
59
60
61
62
63
64
65
66
67
68
69
70
const forEachSecond = (callback, start, data) => {
for (let i = start; i < data.length - 1; i += 2) {
callback(i, data);
}
};
const validateCases = cases => cases.length >= 3 && cases.length % 2 !== 0;
const validateTemplate = template => {
// every second string should contain "->"
let everySecondIsArrow = true;
forEachSecond(
index => {
const nextTemplate = template[index];
everySecondIsArrow =
everySecondIsArrow &&
nextTemplate &&
nextTemplate.trim().includes('->');
},
1,
template
);
// the last but one should contain "_" followed by "->"
const lastButOne = template[template.length - 2];
const lastButOneIsDefault =
(lastButOne && lastButOne.indexOf('_') < lastButOne.indexOf('->')) || false;
return everySecondIsArrow && lastButOneIsDefault;
};
// internal helper to pluralize the string case/cases
const pluralizeCasesString = amount => (amount === 1 ? 'case' : 'cases');
module.exports = (...args) => {
const [template, ...cases] = args;
if (!validateCases(cases)) {
throw new TypeError(
'Looks like there is not at least one case definition or the default case is missing.'
);
} else if (!validateTemplate(template)) {
throw new TypeError(
'The syntax declaring the cases seems to be incorrect.'
);
}
const casesMap = new Map();
forEachSecond(
index => {
casesMap.set(cases[index], cases[index + 1]);
},
0,
cases
);
const finalCasesCount = casesMap.size;
const passedCasesCount = (cases.length - 1) / 2;
if (finalCasesCount !== passedCasesCount) {
throw new Error(
`Computed ${finalCasesCount} final ${pluralizeCasesString(
finalCasesCount
)}, but got ${passedCasesCount} ${pluralizeCasesString(
passedCasesCount
)} passed.`
);
}
return data =>
casesMap.has(data) ? casesMap.get(data) : cases[cases.length - 1];
};