This repository has been archived by the owner on Aug 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathreusables.js
executable file
·98 lines (87 loc) · 2.54 KB
/
reusables.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
export function isArrayOfType(value, ofType, index = 0) {
return value instanceof Array &&
Object.prototype.hasOwnProperty.call(value, index) &&
(ofType === String
? typeof value[index] === "string"
: value[index] instanceof ofType)
? true
: false;
}
export function isNumber(x) {
return !isNaN(parseFloat(x)) && isFinite(x);
}
export function arrayEqual(a, b, byOrder = false) {
return byOrder
? Object.keys(a)
.map((x) => a[x] === b[x])
.reduce((p, n) => (p ? n : p), true)
: [...new Set(a.filter((x) => !new Set(b).has(x)))].length === 0;
}
export function transpose(table) {
const tableSize = table
.map((row) => row.length)
.reduce((p, n) => Math.max(p, n), 0);
return [...Array(tableSize).keys()].map((index) =>
table.map((row) => row[index])
);
}
export function* makeGenerator(x) {
yield* x;
}
function* createIterGenerator(data, func, abort = () => false) {
let i = 0;
for (const iteration of data) {
if (abort()) return;
const modifiedRow = func(iteration, i++);
if (modifiedRow) {
yield modifiedRow;
}
}
}
export function iter(data, func, abort = () => false) {
return Array.from(createIterGenerator(data, func, abort));
}
export function chain(data, ...operations) {
return Array.from(
iter(
data,
operations.reduce(
(p, n) => (x, i) => {
const prev = p(x, i);
const next = prev ? n(prev, i) : false;
return next === true ? prev : next;
},
(x) => x
)
)
);
}
export function xSplit(stringToSplit, ...patterns) {
return patterns.reduce(
(prev, next) =>
prev
.map((str) => str.split(next))
.reduce((p, n) => [...p, ...n], []),
[stringToSplit]
);
}
export function xReplace(stringToReplace, ...patterns) {
return patterns.reduce(
(prev, next) => prev.split(next[0]).join(next[1]),
stringToReplace
);
}
export function xContains(stringToFilter, ...patterns) {
return patterns.filter((pattern) => stringToFilter.includes(pattern));
}
export function hashCode(str) {
let hash = 0;
let char;
if (str.length === 0) return hash;
for (let i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash;
}
return hash;
}