Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Learn More

Step Counter - JavaScript (Basic) Certification test solution | HackerRank

1 min read


Solution:



 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
const counter = (
    function counter() {
        let value = 0;
        return {
            getValue: function() {
                return value;
            },
            changeBy: function (k) {
                value += k;
            }
        }
    }
)();

function getFixedCounter(k) {
    let myCounter = counter;
    return {
        increment: () => {
            myCounter.changeBy(k);
        },
        decrement: () => {
            myCounter.changeBy(-k);
        },
        getValue: () => {
            return myCounter.getValue();
        }
    }
}

console.log(counter.getValue());
counter.changeBy(10);
counter.changeBy(20);
console.log(counter.getValue());
Labels : #hackerrank ,#hackerrank certification ,#javascript (basic) ,

Post a Comment