-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (50 loc) · 1.67 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
const assert = (isTrue, message) => {
if (isTrue) {
throw new Error(message || 'Ошибка');
}
}
const filterForMoreOrLess = (arr) => {
assert(arr.length <= 0, 'Переданный массив пуст');
const resultFilter = arr;
resultFilter.sort().reverse();
return {
more: resultFilter.slice(0, resultFilter.length / 2),
less: resultFilter.slice(resultFilter.length / 2)
}
}
filterOnType = (arr) => {
const resultFilter = {};
for (let itemArr of arr) {
if (!resultFilter[typeof itemArr]) {
resultFilter[typeof itemArr] = [];
}
resultFilter[typeof itemArr].push(itemArr);
}
return resultFilter;
}
const filterArray = (arr, typeFilter) => {
assert(!Array.isArray(arr), 'Переданные данные не являются массивом');
assert(
(
arr.includes(null)
|| arr.includes(undefined)
|| arr.includes(NaN)
),
'Неправильный формат данных уберить undefined, NaN или null',
);
assert(arr.length <= 0, 'Переданный массив пуст');
assert(!typeFilter, 'Тип фильтра не указан');
let resultFunction;
if (typeFilter === 'filterOnType') {
resultFunction = filterOnType(arr);
} else if (typeFilter === 'filterForMoreOrLess') {
assert(
arr.find((item) => typeof item !== 'string'),
'Этот тип фильтра принимает только строки',
);
resultFunction = filterForMoreOrLess(arr);
}
return resultFunction;
}
console.log(filterArray(['123'], 'filterOnType'));
console.log(filterArray(['123', '1', 'Hello!', '', 'Hello!', 'Hello!'], 'filterForMoreOrLess'));