擲出前兩天學到的閉包來解決這一關卡(►__◄)
EASY
Write a function createCounter
. It should accept an initial integer init
. It should return an object with three functions.
The three functions are:
increment()
increases the current value by 1 and then returns it.decrement()
reduces the current value by 1 and then returns it.reset()
sets the current value to init
and then returns it.宣告createCounter
函示,該函示先接受初始整數init
作為參數,它應該返回有三個函示的物件。
increment()
將當前的值+1然後返回decrement()
將當前的值-1然後返回reset()
將當前的值重置為init
後返回i
,所以在外部作用域宣告一個變數init
把i
初始值存起來。createCounter=(i)=>{
let init = i;
return {
increment:()=>++i,
decrement:()=>--i,
reset:()=>{
i=init;
return i
},
}
}
let counter = createCounter(5);
let case1 = [
counter.increment(),
counter.reset(),
counter.decrement()
]
console.log(case1);// [6, 5, 4]
counter = createCounter(0);
let case2 = [
counter.increment(),
counter.increment(),
counter.decrement(),
counter.reset(),
counter.reset(),
];
console.log(case2);// [1, 2, 1, 0, 0]