once

by Vladymyr Shevchuk

JavaScript

const once = fn => (...args) => {
  if (!fn.called) {
    fn.called = true;
    return fn.apply(fn, args);
  }
};

const hello = name => console.log(`hello ${name}!`);
const wrappedHello = once(hello);

wrappedHello('Vasya');
wrappedHello('Petya');
wrappedHello('Ira');


// ======== 

const severalTimes = (func, times) => {
    let result;
    return (...args) => {
      if (--times > 0) {
        result = func.apply(this, args);
      }
      if (times <= 1) func = null;
      return result;
    };
};

const once2 = severalTimes(hello, 1);

console.error(once2);
//const wrappedHello2 = once2(hello);

//wrappedHello2('Vasya');
//wrappedHello2('Petya');
//wrappedHello2('Ira');