forked from thmoon-team/IU5-Frontend-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4.js
36 lines (34 loc) · 1.26 KB
/
4.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
/**
* починить функцию memoize(func),
* на вход принимает функцию
* на выходе получаем функцию, которая умеет запоминать последний результат вызова
* примеры:
* const add = (a) => a * 2;
* const memozedAdd = memoize(add)
* memozedAdd(1) -> {cache: false, result: 2}
* memozedAdd(1) -> {cache: true, result: 2}
* memozedAdd(2) -> {cache: false, result: 4}
* memozedAdd(1) -> {cache: false, result: 2}
* memozedAdd(2) -> {cache: false, result: 4}
* memozedAdd(2) -> {cache: true, result: 4}
*/
function memoize(func) {
let context = {args: [], result: 0, func: func,
run(...args) {
if (this.args && args.every((value, index) => value === this.args[index]))
return {cache: true, result: this.result};
this.result = func(...args);
this.args = args;
return {cache: false, result: this.result};
}}
return context.run;
}
module.exports = memoize;
/*const add = (a) => a * 2;
const memozedAdd = memoize(add);
console.log(memozedAdd(1));
console.log(memozedAdd(1));
console.log(memozedAdd(2));
console.log(memozedAdd(1));
console.log(memozedAdd(2));
console.log(memozedAdd(2));*/