-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounter.js
34 lines (30 loc) · 819 Bytes
/
counter.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
/**
* @param {number} n
* @return {Function} counter
*/
//This is the most efficient solution i could come up with
var createCounter = function(n) {
return function() {
return n++
};
};
// The below example might uses more memory due to closure variable
var createCounterv2 = function(n) {
let number
return function() {
number = (typeof number !== 'number') ? n : number + 1
return number;
};
};
const counter = createCounter(-2)
console.log(counter()) // -2
console.log(counter()) // -1
console.log(counter()) // 0
console.log(counter()) // 1
console.log(counter()) // 2
const counter2 = createCounterv2(-2)
console.log(counter2()) // -2
console.log(counter2()) // -1
console.log(counter2()) // 0
console.log(counter2()) // 1
console.log(counter2()) // 2