You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
999 B

4 years ago
  1. import _arity from "./internal/_arity.js";
  2. import _curry1 from "./internal/_curry1.js";
  3. /**
  4. * Accepts a function `fn` and returns a function that guards invocation of
  5. * `fn` such that `fn` can only ever be called once, no matter how many times
  6. * the returned function is invoked. The first value calculated is returned in
  7. * subsequent invocations.
  8. *
  9. * @func
  10. * @memberOf R
  11. * @since v0.1.0
  12. * @category Function
  13. * @sig (a... -> b) -> (a... -> b)
  14. * @param {Function} fn The function to wrap in a call-only-once wrapper.
  15. * @return {Function} The wrapped function.
  16. * @example
  17. *
  18. * const addOneOnce = R.once(x => x + 1);
  19. * addOneOnce(10); //=> 11
  20. * addOneOnce(addOneOnce(50)); //=> 11
  21. */
  22. var once =
  23. /*#__PURE__*/
  24. _curry1(function once(fn) {
  25. var called = false;
  26. var result;
  27. return _arity(fn.length, function () {
  28. if (called) {
  29. return result;
  30. }
  31. called = true;
  32. result = fn.apply(this, arguments);
  33. return result;
  34. });
  35. });
  36. export default once;