-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExamples.js
More file actions
909 lines (760 loc) · 22.7 KB
/
Copy pathExamples.js
File metadata and controls
909 lines (760 loc) · 22.7 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
function IsPrime(num) {
let root = Math.round(Math.sqrt(num))
for (let i = 2; i <= root; i++) {
if (num % i === 0) return false;
}
return num > 1;
}
// const isPrime = n =>
// ![...Array(n).keys()]
// .slice(2)
// .map(i => !(n%i))
// .includes(true)
// &&
// ![0,1].includes(n)
//// вывести все простые числа до N
let a = 100
function getAllPrimes(n) {
let arr = []
for (let i = 2; i <= n; i++){ arr.push(i )}
let set = new Set(arr);
set.forEach(el => {
let tmp = el
let i = 2;
while (tmp < n) {
tmp = el * i
set.delete(tmp)
i++
}
})
return set
}
console.log(getAllPrimes(a))
///////
function Factorial(n) {
let cache = {}
return (n) => {
if (cache[n]){
console.log('Fetching from cache');
return cache[n]
}
else {
console.log('Calculating result');
let result = !!n && 1;
if (result){
for (let i = 1; i <= n; i++){
result *= i;
cache[i] = result;
}
cache[n] = result;
}
return n > 0 && result;
}
}
}
let memFact = Factorial();
console.log( memFact(0) ) // calc
console.log( memFact(4) ) // fetch
// console.log( memFact(0) ) // false
// console.log( memFact() ) // false
// console.log( memFact(1) ) //1
let memFib = ((n) => {
let cache = {}
cache[0] = 0;
cache[1] = 1;
return (n) => {
if (cache[n]){
console.log('Fetching from cache');
return cache[n]
}
else {
console.log('Calculating result');
let result = 0;
if (n >= 0){
for (let i = 2; i <= n; i++){
result = cache[i-2] + cache[i-1]
cache[i] = result;
}
cache[n] = result;
}
return n >= 0 && result;
}
}
})()
// let memFib = fib();
console.log( memFib() ) // false
console.log( memFib(0) ) // 0
console.log( memFib(-1) ) // false
///////
function isSorted(arr) {
if (arr.length > 1) {
for (let i = 0; i < arr.length; i++){
if (arr[i] > arr[i+1]) return false
}
}
return true;
}
///////
function customFilter(arr, callback){
let result = []
for (let i = 0; i < arr.length; i++ ){
if (callback(arr[i], i, arr)) result.push(arr[i])
}
return result
}
Array.prototype.filter = function (fun) {
var filtered = [];
for(let i = 0; i < this.length; i++) {
if (fun(this[i], i, this)) filtered.push(this[i]);
}
return filtered;
};
////////
function duplicateCount(text){
text = text.toLowerCase();
let map = new Map();
let count = 0;
text.split("").forEach(el => {
if (!map.has(el)) map.set(el, 1)
else map.set(el, map.get(el) + 1)
})
for (let value of map.values()) {
if (value > 1) count++;
}
return count;
}
///////////
let user = {
name: "John",
money: 1000,
[Symbol.toPrimitive](hint) {
console.log(`hint: ${hint}`);
return hint == "string" ? `{name: "${this.name}"}` : this.money;
}
};
// демонстрация результатов преобразований:
console.log(user); // hint: string -> {name: "John"}
console.log(+user); // hint: number -> 1000
console.log(user + 500); // hint: default -> 1500
///////////////
//DEBOUNCING
function debounce(func, ms) {
let canRun = true;
return function() {
if (canRun) {
canRun = false;
func.apply(this, arguments)
setTimeout(() => {
canRun = true;
}, ms)
}
}
}
let f = debounce(console.log, 1000);
f(1); // выполняется немедленно
f(2); // проигнорирован
setTimeout( () => f(3), 100); // проигнорирован (прошло только 100 мс)
setTimeout( () => f(4), 1100); // выполняется
setTimeout( () => f(5), 1500); // проигнорирован
//////////////////////
let arr = [2, -1, 2, 3, -9]
function getMaxSubSum(arr) {
let maxSum = 0;
let partialSum = 0;
for (let item of arr) { // для каждого элемента массива
partialSum += item; // добавляем значение элемента к partialSum
maxSum = Math.max(maxSum, partialSum); // запоминаем максимум на данный момент
if (partialSum < 0) partialSum = 0; // ноль если отрицательное
}
return maxSum;
}
//////////////////
let arr = ["nap", "teachers", "cheaters", "PAN", "ear", "era", "hectares", "biba"];
function anagramClean(arr) {
let obj = {}
for (let el of arr){
let sorted = el.toLowerCase().split("").sort().join("")
if (!obj.hasOwnProperty(sorted)) {
obj[sorted] = [el]
} else {
obj[sorted].push(el)
}
}
return Object.values(obj)
}
console.log(anagramClean(arr))
///////////////// Генерация скобочных последовательностей
let k = 6
let init = []
let cnt = 0
let ind = 0
function f(cnt, ind, k, init) {
console.warn(cnt, ind, k, init)
if (cnt <= k - ind - 2) {
init[ind] = '('
f(cnt + 1, ind + 1, k, init)
}
if (cnt > 0){
init[ind] = ')'
f(cnt - 1, ind + 1, k, init)
}
if (ind === k && cnt == 0) console.log(init)
}
f(cnt, ind, k, init)
/////////////////
function sumClosure(a) {
let currentSum = a;
function f(b) {
currentSum += b;
// console.log(currentSum)
return f;
}
f.toString = function() {
return currentSum;
};
return f;
}
let a = +sumClosure(2)(3) ;
console.log(a)
/////// односвязный список
let list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: null
}
}
}
};
function printList(list) {
list.next && printList(list.next)
console.log(list.value)
}
function printListCycle(list) {
let tmp = list
while (tmp) {
console.log(tmp.value)
tmp = tmp.next
}
}
printList(list)
printListCycle(list)
//////// двусвязный список
function Node(val) {
this.data = val;
this.prev = null;
this.next = null;
}
function LinkedList() {
this.head = null;
this.tail = null;
this.addAtFront = function (val) {
if (this.head === null) { //If first node
this.head = new Node(val);
this.tail = this.head;
} else {
var temp = new Node(val);
temp.next = this.head;
this.head.prev = temp;
this.head = temp;
}
};
this.addAtEnd = function (val) {
if (this.tail === null) { //If first node
this.tail = new Node(val);
this.head = this.tail;
} else {
var temp = new Node(val);
temp.prev = this.tail;
this.tail.next = temp;
this.tail = temp;
}
};
this.removeAtHead = function () {
var toReturn = null;
if (this.head !== null) {
toReturn = this.head.data;
if (this.tail === this.head) {
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
this.head.prev = null;
}
}
return toReturn;
};
this.removeAtTail = function () {
var toReturn = null;
if (this.tail !== null) {
toReturn = this.tail.data;
if (this.tail === this.head) {
this.head = null;
this.tail = null;
} else {
this.tail = this.tail.prev;
this.tail.next = null;
}
}
return toReturn;
};
this.each = function (f) {
var curr = this.head;
while (curr !== null) {
f(curr);
curr = curr.next;
}
};
this.printList = function () {
this.each(function (item) {
console.log(item.data);
});
};
}
var testList = new LinkedList();
var runTests = function () {
testList.addAtFront("Second");
testList.addAtFront("First");
testList.addAtEnd("Third");
testList.addAtEnd("Fourth");
testList.printList();
testList.removeAtHead();
testList.removeAtTail();
testList.printList();
testList.removeAtHead();
testList.removeAtHead();
testList.printList();
};
runTests()
////////// Delay decorator
function f(x) {
console.log(x);
}
function delay(func, timeout) {
return function (...args) {
setTimeout(() => func.apply(this, args), timeout)
}
}
// создаём обёртки
let f1000 = delay(f, 1000);
let f1500 = delay(f, 1500);
f1000("test", 'huy'); // показывает "test" после 1000 мс
f1500("test2"); // показывает "test" после 1500 мс
/////////// THROTTLING return last execute
function f(a) {
console.log(a)
}
function throttle(func, ms) {
let canRun = true;
let lastArgs;
let lastThis;
let timer;
return function() {
if (canRun) {
func.apply(this, arguments);
canRun = false;
} else {
clearTimeout(timer);
lastArgs = arguments
lastThis = this
}
timer = setTimeout(() => {
canRun = true;
lastArgs && func.apply(lastThis, lastArgs);
lastArgs = null
lastThis = null
}, ms)
}
}
// f1000 передаёт вызовы f максимум раз в 1000 мс
let f1000 = throttle(f, 1000);
f1000(1); // показывает 1
f1000(2); // (ограничение, 1000 мс ещё нет)
f1000(3); // (ограничение, 1000 мс ещё нет)
f1000(4); // (ограничение, 1000 мс ещё нет)
f1000(5); // (ограничение, 1000 мс ещё нет)
f1000(6); // (ограничение, 1000 мс ещё нет)
f1000(7); // (ограничение, 1000 мс ещё нет)
// когда 1000 мс истекли ...
// ...выводим 3, промежуточное значение 2 было проигнорировано
/////////// THROTTLING returns all execs with delay
function f(a) {
console.log(a)
}
function throttle(func, ms) {
let canRun = true;
let argsArray = [];
let timer;
return function() {
if (canRun) {
func.apply(this, arguments);
canRun = false;
} else {
clearTimeout(timer);
argsArray.push({
arguments,
currThis: this
})
}
let next = () => {
timer = setTimeout(() => {
canRun = true;
let el = argsArray[0]
argsArray.shift()
if ( el) {
func.apply(el.currThis, el.arguments);
next()
}
}, ms)
}
next()
}
}
// f1000 передаёт вызовы f максимум раз в 1000 мс
let f1000 = throttle(f, 1000);
f1000(1); // показывает 1
f1000(2); // (ограничение, 1000 мс ещё нет)
f1000(3); // (ограничение, 1000 мс ещё нет)
f1000(4); // (ограничение, 1000 мс ещё нет)
f1000(5); // (ограничение, 1000 мс ещё нет)
f1000(6); // (ограничение, 1000 мс ещё нет)
f1000(7); // (ограничение, 1000 мс ещё нет)
// когда 1000 мс истекли ...
// ...выводим 3, промежуточное значение 2 было проигнорировано
////////////
function checkBrackets(stroke) {
let array = [...stroke]
let isCheckable = true;
let position = null;
let position1 = null;
let position2 = null;
while(isCheckable) {
position = stroke.indexOf('()')
position1 = stroke.indexOf('[]')
position2 = stroke.indexOf('{}')
function findAndCut(position) {
array.splice(position, 2)
stroke = array.join("")
isCheckable = true
}
if (~position) {
findAndCut(position)
continue;
} else {
isCheckable = false
}
if (~position1) {
findAndCut(position1)
continue;
} else {
isCheckable = false
}
if (~position2) {
findAndCut(position2)
} else {
isCheckable = false
}
}
console.log(array.join(""))
return array.length === 0
}
console.log(checkBrackets('[{(([]))}([])]'))
////
function validParentheses(parens){
let n = 0;
for (let i = 0; i < parens.length; i++) {
if (parens[i] === '(') n++;
if (parens[i] === ')') n--;
if (n < 0) return false;
}
return n === 0;
}
//////////////
function compressArray(array) {
let arrayLcl = array.sort((a, b) => a - b)
if (arrayLcl.length < 2) return arrayLcl.join();
let result = "";
let startDia = arrayLcl[0];
result += startDia;
for (let i = 1; i < arrayLcl.length; ++i) {
if(arrayLcl[i] - arrayLcl[i - 1] > 1) {
if (arrayLcl[i - 1] !== startDia) result += `-${arrayLcl[i-1]}`
result += `,${arrayLcl[i]}`
startDia = arrayLcl[i]
}
if (i === arrayLcl.length && arrayLcl[i] !== startDia) result += `-${arrayLcl[i]}`
}
return result
}
let arr = [3, 2, 1, 5, 6, -1, 10]
console.log(compressArray(arr))
///////////////
// Rfhhbhjdfybt
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args);
} else {
return function(...args2) {
return curried.apply(this, args.concat(args2));
}
}
};
}
////////////////
Function.prototype.defer = function (ms) {
let self = this
return function(){
setTimeout(() => self.apply(this, arguments), ms)
}
}
console.log('defer0')
function f(asd) {
console.log('defer1 ' + asd)
}
f.defer(1000)('хуй')
////////////////
/**
* Необходимо написать функцию, которая на вход принимает урл,
* асинхронно ходит по этому урлу GET запросом и возвращает данные (json).
* Для получении данных можно использовать $.get или fetch.
* Если во время запроса произошла ошибка, то пробовать запросить ещё 5 раз.
* Если в итоге информацию получить не удалось, вернуть ошибку "Заданный URL недоступен".
*/
function get(url, count = 5) {
return fetch(url)
// .then((res) => res)
.catch((err) => {
if (count === 0) {
throw new Error('Заданный URL недоступен')
} else {
return get(url, count--)
}
})
}
get(url)
.then(res => console.log(res))
.catch(err => console.error(err))
function get(url, count = 5) {
return fetch()
.catch(err => count === 0 ? throw 'asd' : get(url, count--));
}
/////////
function func () {
const promise = new Promise(resolve => {
resolve({
toA: 2,
toB: 1,
});
});
return {
a: promise.then(res => res.toA),
b: promise.then(res => res.toB)
}
}
//////////////
// Дана строка (возможно, пустая), состоящая из букв A-Z:
// // AAAABBBCCXYZDDDDEEEFFFAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB
// // Нужно написать функцию RLE, которая на выходе даст строку вида:
// // A4B3C2XYZD4E3F3A6B28
// // И сгенерирует ошибку, если на вход пришла невалидная строка.
// // Пояснения:
// // Если символ встречается 1 раз, он остается без изменений;
// // Если символ повторяется более 1 раза, к нему добавляется количество повторений.
function RLE(str) {
if (typeof str !== "string") return new Error('invalid')
let result = '';
let count = 1;
let char = str.length ? str[0] : undefined;
let i = 0;
for(i; i < str.length; i++) {
count = 1
while(str[i] === char) {
count++;
i++;
}
char = str[i]
result += `${count !== 1 ? count : ''}${i !== str.length ? char : ''}`
}
return result
}
console.log(RLE('AAAABBBCCXYZDDDDEEEFFFAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBB') === 'A4B3C2XYZD4E3F3A6B28')
///// СВОЙ Promise.all !!!!!!!!!!! ура
function parallel(funcArray, doneAll) {
let results = []
const outerPromise = (funcInPromise) => {
return new Promise(resolve => {
funcInPromise(done(resolve))
})
}
const done = (resolve) => {
return (data) => {
results.push(data)
resolve()
}
}
const promise = funcArray.reduce((prevPromise, func) => {
return prevPromise.then(() => outerPromise(func))
}, Promise.resolve() );
promise.then(() => doneAll(results))
}
var a = function(done) {
setTimeout(function() {
done('result a');
}, 300);
};
var b = function(done) {
setTimeout(function() {
done('result b');
}, 200);
};
parallel([a,b], function(results) {
console.log(results); // ['result a', 'result b']
});
//////////////////
// палиндром
function palindrom(str) {
let regexp = /\w/gi;
const regexped = str.match(regexp).join("").toLocaleLowerCase();
for (let i = 0; i < regexped.length; i++) {
const last = regexped[regexped.length - 1 - i]
if (i === last) return true;
if (regexped[i] !== last) return false;
}
return true
}
/////////////
/*
Реализовать функцию memoize, которая принимает в качестве аргумента функцию
и возвращает мемоизированную функцию-обертку. Эта функция-обертка внутри вызывает
переданную в memoize функцию, но при этом кэширует результат и при последующих вызовах
с теми же аргументами возвращает результат из кэша.
Вторым необязательным аргументом функция memoize принимает таймаут в миллисекундах,
в течение которого данные хранятся в кэше.
/
// Пример:
// функция, которая реализует какие-то сложные вычисления
const calculateSometh = () => { / ...some calculations... */ }
// таймаут - одна секунда
const cacheTimeout = 1000;
const memoizedCalcualteSometh = memoize(calculateSometh, cacheTimeout);
memoizedCalcualteSometh(1); // вызывает внутри calculateSometh(1) и возвращает результат
memoizedCalcualteSometh(1); // не вызывает calculateSometh, а возвращает сохраненное значение из кэша
memoizedCalcualteSometh(2); // вызывает внутри calculateSometh(2), т.к. аргумент изменился
memoizedCalcualteSometh(1); // не вызывает calculateSometh, по-прежнему из кэша от первого вызова
// опять вызывает calculateSometh(1), т.к. с момента предыдущего вызова прошло больше одной секунды
setTimeout(() => memoizedCalcualteSometh(1), 2000)
function memoize(func, ms){
let cache = {};
return function (...args) {
const argsStr = args.toString()
if (cache[argsStr]) return cache[argsStr]
cache[argsStr] = func.apply(this, args)
if (ms){
setTimeout(() => {
delete cache[argsStr]
}, ms)
}
}
}
///////////////
var moveZeros = function (arr) {
let lastPuttedZero = arr.length - 1;
if(lastPuttedZero < 0) return arr;
for(let i = 0; i < arr.length; i++){
if(arr[i] === 0 && lastPuttedZero > i){
arr.splice(i, 1)
arr.push(0)
lastPuttedZero--;
i--;
}
}
return arr;
}
moveZeros(["a",0,"b","c","d",1,1,3,1,9,0,0,9,0,0,0,0,0,0,0])
//////////////
function convertToRoman(num) {
let roman = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
};
let str = '';
for (let i of Object.keys(roman)) {
let q = Math.floor(num / roman[i]);
num -= q * roman[i];
str += i.repeat(q);
}
return str;
}
console.log(convertToRoman(11990))
//////////
const array1 = [[1,1,1,1,1,1,1],
[1,2,2,2,2,2,1],
[1,2,3,3,3,2,1],
[1,2,3,4,3,2,1],
[1,2,3,3,3,2,1],
[1,2,2,2,2,2,1],
[1,1,1,1,1,1,1],
]
const array2 = [[ 1, 2, 3, 4, 5],
[16,17,18,19, 6],
[15,24,25,20, 7],
[14,23,22,21, 8],
[13,12,11,10, 9]
]
const array = [[ 1, 2, 3, 4],
[12,13,14, 5],
[11,16,15, 6],
[10, 9, 8, 7]
]
const array3 = [[1,2,3],
[8,9,4],
[7,6,5]
]
function snail(matrix){
if (matrix.length < 2) return matrix[0];
const countSquare = Math.ceil(matrix[0].length / 2);
let result = [];
for (let i = 0; i <= countSquare; i++){
for (let j = i; j < matrix[i].length - i; j++){
result.push(matrix[i][j]);
}
for (let r = i + 1; r < matrix.length - i - 1; r++){
result.push(matrix[r][matrix[r].length - 1 - i]);
}
for (let b = matrix[i].length - i - 1; b >= i; b--){
result.push(matrix[matrix.length - 1 - i][b]);
}
for (let l = matrix.length - i - 2; l > i ; l--){
result.push(matrix[l][i]);
}
}
if (matrix.length % 2 !== 0) result.pop();
return result;
}
function snail_bestPractise(array) {
let vector = [];
while (array.length) {
vector.push(...array.shift());
array.map(row => vector.push(row.pop()));
array.reverse().map(row => row.reverse());
}
return vector;
}
console.log(snail(array))
/////////