Skip to content

How to create a function that executes only once

Daisho Komiyama edited this page Mar 5, 2020 · 1 revision

Today, I learned how to create a function that runs only once without using global variables, thanks to Will Sentence.

const oncify = fn => {
    let counter = 0;
    const inner = input => {
        if (counter === 0) {
            const output = fn(input);
            counter++;
            return output;
        }
        return false;
    };
    return inner;
};

const add3 = num => num + 3;
const oncifyAdd3 = oncify(add3);

oncifyAdd3(5); //Returns 8

Something similar to that can be achieved by declaring the variable counter in global scope. But if you want to keep global as clean as possible, use this method described above, AKA Closure.

Clone this wiki locally