Restricting the Number of Times a Function Can be Called in JavaScript

微信扫一扫,分享到朋友圈

Restricting the Number of Times a Function Can be Called in JavaScript

By using functions that can wrap other functions, the management of how many times a function is called can be greatly simplified. For example of the custom logic, here is normally how a function is called only once:

let called = false;
function oneTimeIncrement() {
  if (!called) {
    value += 1;
  }
  called = true;

  return value;
}

console.log(oneTimeIncrement());
// 1
console.log(oneTimeIncrement());
// 1
console.log(oneTimeIncrement());
// 1

By using a wrapper function the surrounding logic around it can be eliminated. Here the advantage is not that big, but used across an entire codebase, it can significantly reduce custom logic:

let value = 0;
function increment() {
  value += 1;
  return value;
}

const oneTimeIncrement = once(increment);
console.log(oneTimeIncrement());
// 1
console.log(oneTimeIncrement());
// 1
console.log(oneTimeIncrement());
// 1

Here is the once
function:

function once(callback) {
  let called = false,
    result = undefined;
  return () => {
    if (called === false) {
      result = callback(...arguments);
    }
    called = true;
    return result;
  }
}

This tactic can also be extended to support functions called a number of times if called
is turned into a number. Lodash has aonce function and abefore function to handle multiple times.

Github Location https://github.com/Jacob-Friesen/obscurejs/blob/master/2018/once.js

微信扫一扫,分享到朋友圈

Restricting the Number of Times a Function Can be Called in JavaScript

Google Pays Apple Billions of Dollars to Be Safari’s Default Search Engine

上一篇

Customer journeys build communities

下一篇

你也可能喜欢

Restricting the Number of Times a Function Can be Called in JavaScript

长按储存图像,分享给朋友