Repository navigation
Expand file tree
/
Copy pathjavascript_algorithms.js
More file actions
296 lines (249 loc) · 7.77 KB
/
Copy pathjavascript_algorithms.js
File metadata and controls
296 lines (249 loc) · 7.77 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// JS Compiler
class Compiler {
compile(program) {
const ast1 = this.pass1(program);
const ast2 = this.pass2(ast1);
return this.pass3(ast2);
}
tokenize(program) {
const regex = /[-+*/()[\]]|[A-Za-z]+|\d+/g;
const tokens = [];
let match;
while ((match = regex.exec(program)) !== null) {
const tok = match[0];
tokens.push(/^\d+$/.test(tok) ? parseInt(tok, 10) : tok);
}
return tokens;
}
pass1(program) {
this.tokens = this.tokenize(program);
this.pos = 0;
const args = this.parseArgs();
const ast = this.parseExpression(args);
return ast;
}
current() {
return this.pos < this.tokens.length ? this.tokens[this.pos] : null;
}
eat() {
return this.tokens[this.pos++];
}
parseArgs() {
if (this.current() !== '[') throw new SyntaxError("Expected '['");
this.eat();
const args = [];
while (typeof this.current() === 'string' && /^[A-Za-z]+$/.test(this.current())) {
args.push(this.eat());
}
if (this.current() !== ']') throw new SyntaxError("Expected ']'");
this.eat();
return args;
}
parseExpression(args) {
let node = this.parseTerm(args);
while (this.current() === '+' || this.current() === '-') {
const op = this.eat();
node = { op: op, a: node, b: this.parseTerm(args) };
}
return node;
}
parseTerm(args) {
let node = this.parseFactor(args);
while (this.current() === '*' || this.current() === '/') {
const op = this.eat();
node = { op: op, a: node, b: this.parseFactor(args) };
}
return node;
}
parseFactor(args) {
const tok = this.current();
if (typeof tok === 'number') {
this.eat();
return { op: 'imm', n: tok };
} else if (typeof tok === 'string' && /^[A-Za-z]+$/.test(tok)) {
const idx = args.indexOf(tok);
this.eat();
return { op: 'arg', n: idx };
} else if (tok === '(') {
this.eat();
const node = this.parseExpression(args);
if (this.current() !== ')') throw new SyntaxError("Expected ')'");
this.eat();
return node;
} else {
throw new SyntaxError(`Unexpected token ${tok}`);
}
}
pass2(ast) {
if (ast.op === 'imm' || ast.op === 'arg') return ast;
const a = this.pass2(ast.a);
const b = this.pass2(ast.b);
if (a.op === 'imm' && b.op === 'imm') {
let val;
switch (ast.op) {
case '+': val = a.n + b.n; break;
case '-': val = a.n - b.n; break;
case '*': val = a.n * b.n; break;
case '/': val = Math.floor(a.n / b.n); break;
}
return { op: 'imm', n: val };
} else {
return { op: ast.op, a: a, b: b };
}
}
pass3(ast) {
return this.emit(ast);
}
emit(node) {
if (node.op === 'imm') return [`IM ${node.n}`];
if (node.op === 'arg') return [`AR ${node.n}`];
const code = [];
code.push(...this.emit(node.a));
code.push('PU');
code.push(...this.emit(node.b));
code.push('SW');
code.push('PO');
const opMap = { '+': 'AD', '-': 'SU', '*': 'MU', '/': 'DI' };
code.push(opMap[node.op]);
return code;
}
}
const compiler = new Compiler();
const asm = compiler.compile("[a b] (a + 2) * (b + 3)");
console.log(asm.join("\n"));
// Sum of Intervals
function sumIntervals(intervals) {
intervals.sort((a, b) => a[0] - b[0]);
let totalLength = 0;
let currentInterval = intervals[0];
for (let i = 1; i < intervals.length; i++) {
const nextInterval = intervals[i];
if (currentInterval[1] >= nextInterval[0]) {
currentInterval[1] = Math.max(currentInterval[1], nextInterval[1]);
} else {
totalLength += currentInterval[1] - currentInterval[0];
currentInterval = nextInterval;
}
}
totalLength += currentInterval[1] - currentInterval[0];
return totalLength;
}
// Get middle character
function getMiddle(word) {
if (word.length % 2 !== 0) return word[((word.length - 1) / 2)]
return word[(word.length / 2) - 1] + word[word.length / 2]
}
// Replace With Alphabet Position
function alphabetPosition(str) {
const alphabets = Array.from({ length: 26 }, (_, index) => String.fromCharCode(65 + index)).map(el => el.toLowerCase())
alphabets.unshift('0')
return str.split('').filter(l => alphabets.includes(l.toLowerCase())).map(alphabet => {
if (alphabets.includes(alphabet.toLowerCase())) return alphabets.findIndex(el => el === alphabet.toLowerCase())
}).filter(el => el != '0').join(' ')
}
// Persistent Bugger
function persistence(num) {
if (num <= 0) return null
if (''.concat(num).length === 1) return 0
let invoked = 1;
function innerPersistence(num2) {
const num2Multiplication = ''
.concat(num2)
.split('')
.map(n => parseInt(n))
.reduce((p, n) => p * n, 1);
return num2Multiplication
}
let multiplication = innerPersistence(num)
while (''.concat(multiplication).length !== 1) {
invoked++
multiplication = innerPersistence(multiplication)
}
if (''.concat(multiplication).length === 1) return invoked
}
// Human Readable Duration Format
function formatDuration(seconds) {
if (seconds === 0) return 'now';
let remain = seconds;
function calculateValue(format) {
const calculated = remain / format > 0.5 ? Math.floor(remain / format) : Math.round(remain / format);
remain %= format
return calculated
}
const in_seconds = {
year: 31536000,
day: 86400,
hour: 3600,
minute: 60,
second: 1
}
const values = []
for (let i = 0; i < Object.values(in_seconds).length; i++) {
values.push(calculateValue(Object.values(in_seconds)[i]))
}
values.push(remain)
let res = [];
function stringify(value, unit, secondValue, thirdValue) {
let str = ""
if (value > 0) {
if (value === 1) {
str = `${value} ${unit}`
} else {
str = `${value} ${unit}s`
}
}
res.push(str)
}
for (let i = 0; i < Object.keys(in_seconds).length; i++) {
const current = Object.keys(in_seconds)[i]
const next_step = Object.values(in_seconds)[i + 1]
const next_next_step = Object.values(in_seconds)[i + 2]
stringify(values[i], current, next_step ? next_step : 0, next_next_step ? next_next_step : 0)
}
const result = res.filter(el => el !== '')
if (result.length === 1) return result[0]
else if (result.length === 2) return result.join(' and ')
return result.map((el, index) => {
if (index === result.length - 1) return `and ${el}`
else if (index === result.length - 2) return el
return `${el},`
}).join(' ')
}
// Snailed Array
function snail(arr) {
const snailedFinally = [];
function makeCircle(arr) {
const snailed = [];
if (arr.length === 0) {
return snailed;
}
snailed.push(...arr.shift());
for (let i = 0; i < arr.length; i++) {
snailed.push(arr[i].pop());
}
if (arr.length > 0) {
snailed.push(...arr.pop().reverse());
}
for (let i = arr.length - 1; i >= 0; i--) {
snailed.push(arr[i].shift());
}
return snailed;
}
while (arr.length > 0) {
const result = makeCircle(arr);
snailedFinally.push(...result);
}
return snailedFinally;
}
// Moving Zeros to the End
const moveZeros = arr => [...arr.filter(el => el !== 0), ...arr.filter(el => el === 0)]
// Array Diff
const arrayDiff = (listA, listB) => {
const differed = []
for (let i = 0; i < listA.length; i++) {
if (listB.every(el => el !== listA[i])) {
differed.push(listA[i])
}
}
return differed
}