Discuss / JavaScript / once & memorize

once & memorize

Topic source

Junes_99994

#1 Created at ... [Delete] [Delete and Lock User]

function once(fn, context) {

    return function() {

        if (fn) {

            let f = fn;

            fn = null;

            return f.apply(context || this, arguments);

        }

    };

}

function memorize(fn, context) {

    let mem = {}

    return function() {

        let input = JSON.stringify(arguments)

        return mem[input] || (mem[input] = fn.apply(context || this, arguments));

    }

}


  • 1

Reply