-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrays.js
119 lines (93 loc) · 2.42 KB
/
arrays.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const { greatest, least } = require('./math.js');
const count = (arr, match) => {
const matchFn = typeof match === 'function'
? match
: (item => item === match);
return arr.filter(matchFn).length;
};
const getIndexes = (arr) => Object.keys(arr).map(Number);
const getGreatestIndex = (arr) => greatest(getIndexes(arr));
const getLeastIndex = (arr) => least(getIndexes(arr));
const shiftArray = (negativeArray, amount = null) => {
if (amount === null) {
const leastIndex = getLeastIndex(negativeArray);
if (leastIndex >= 0) {
return negativeArray;
}
amount = -leastIndex;
}
const shifted = [];
for (const [i, val] of Object.entries(negativeArray)) {
shifted[Number(i) + amount] = val;
}
return shifted;
};
const shiftMatrix = (negativeMatrix) => {
const shifted = shiftArray(negativeMatrix);
const leastXIndex = least(shifted.map(getLeastIndex));
return shifted.map(row => shiftArray(row, -leastXIndex));
};
const fillMatrix = (sparseMatrix) => {
const filled = [];
const greatestXIndex = greatest(sparseMatrix.map(getGreatestIndex));
for (let y = 0; y < sparseMatrix.length; y++) {
filled[y] = [];
for (let x = 0; x <= greatestXIndex; x++) {
filled[y][x] = sparseMatrix[y][x];
}
}
return filled;
};
const coordsOf = (matrix, item) => {
for (let y = 0; y < matrix.length; y++) {
for (let x = 0; x < matrix[y].length; x++) {
if (matrix[y][x] === item) {
return [x, y];
}
}
}
return [-1, -1];
};
const eachMatrix = (matrix, eachFn) => {
for (let y = 0; y < matrix.length; y++) {
for (let x = 0; x < matrix[y].length; x++) {
eachFn(matrix[y][x], [x, y], matrix);
}
}
};
const mapMatrix = (matrix, mapFn) => {
const mapped = [];
for (let y = 0; y < matrix.length; y++) {
mapped[y] = [];
for (let x = 0; x < matrix[y].length; x++) {
mapped[y][x] = mapFn(matrix[y][x], [x, y], matrix);
}
}
return mapped;
};
const filterMatrix = (matrix, filterFn) => {
const filtered = [];
eachMatrix(matrix, (item, coords) => {
if (filterFn(item, coords, matrix)) {
filtered.push(item);
}
});
return filtered;
};
const matrixToString = (matrix) => matrix
.map(row => row.join(''))
.join('\n');
module.exports = {
count,
getIndexes,
getGreatestIndex,
getLeastIndex,
shiftArray,
shiftMatrix,
fillMatrix,
coordsOf,
eachMatrix,
mapMatrix,
filterMatrix,
matrixToString
}