Skip to content

Latest commit

 

History

History
49 lines (36 loc) · 781 Bytes

File metadata and controls

49 lines (36 loc) · 781 Bytes

46. implement _.once()

Problem

https://bigfrontend.dev/problem/implement-once

Problem Description

_.once(func) is used to force a function to be called only once, later calls only returns the result of first call.

Can you implement your own once()?

function func(num) {
  return num;
}

const onced = once(func);

onced(1);
// 1, func called with 1

onced(2);
// 1, even 2 is passed, previous result is returned

Solution

/**
 * @param {Function} func
 * @return {Function}
 */
function once(func) {
  let result;
  let isExecuted = false;
  return function (...args) {
    if (!isExecuted) {
      result = func.apply(this, args);
      isExecuted = true;
    }
    return result;
  };
}