The task is to implement a count property that increments every time count is accessed.
The boilerplate code:
function createCounter(): {count: number } {
// your code here
}
When the count is accessed the first time, the getter is expected to return 0. So the initial state before the first access should be -1
let current = -1;
To increment count every time it is accessed, increase the value of current
return {
get count() {
current++;
return current;
}
}
Since a getter is being used, it cannot be increment manually i.e obj.count = 10 will fail.
The final code
function createCounter(): {count: number } {
// your code here
let current = -1;
return {
get count() {
current++;
return current;
}
}
}
That's all folks!
Top comments (0)