-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.js
96 lines (76 loc) · 2.27 KB
/
helpers.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
// --- Arrays ---
Array.prototype.sum = function () {
return this.reduce((a, b) => a + b, 0);
}
Array.prototype.max = function () {
return Math.max(...this);
}
Array.prototype.min = function () {
return Math.min(...this);
}
Array.prototype.countChar = function (char) {
return this.reduce((accumulator, str) => accumulator + str.split(char).length - 1, 0);
}
Array.prototype.compare = function (arr2) {
if (this.length !== arr2.length) return false;
let same = true;
this.forEach((field, index) => {
if (field !== arr2[index]) same = false;
})
return same;
}
Array.prototype.intersection = function (arrB) {
return this.filter(el => arrB.includes(el));
}
// sorted union with eliminated duplicates
Array.prototype.union = function (arrB) {
return [...new Set([...this, ...arrB])].sort();
}
// next 3 are jigsaw operations (first used in 2020 day 20)
// rotations work both for array of strings and array of arrays
Array.prototype.rotateRight = function() {
let newTile = [];
for (let i = 0; i < this[0].length; i++) {
newTile.push("");
}
for (const line of this) {
for (let i = 0; i < line.length; i++) {
if (Array.isArray(line)) newTile[i] = [line[i], ...newTile[i]];
else newTile[i] = line.charAt(i) + newTile[i];
}
}
return newTile;
}
Array.prototype.rotateLeft = function() {
return this.rotateRight().rotateRight().rotateRight();
}
Array.prototype.flip = function() {
let newTile = [];
for (const line of this) {
newTile.push(line.reverse());
}
return newTile;
}
// --- Strings ---
// str.isupper()
String.prototype.isUpper = function () {
return this.toUpperCase() == this;
}
// str.islower()
String.prototype.isLower = function () {
return this.toLowerCase() == this;
}
String.prototype.countChar = function (char) {
return this.split(char).length - 1;
}
String.prototype.setCharAt = function (char, index) {
return this.substring(0, index) + char + this.substring(index + 1);
}
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
// --- Others ---
let chr = String.fromCharCode;
let ord = str => str.charCodeAt(0);
// numpy.zeros()
const zeros = length => Array.from({ length }).map(() => 0);