createPartialWrapper.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var createCtorWrapper = require('./createCtorWrapper');
  2. /** Used to compose bitmasks for wrapper metadata. */
  3. var BIND_FLAG = 1;
  4. /**
  5. * Creates a function that wraps `func` and invokes it with the optional `this`
  6. * binding of `thisArg` and the `partials` prepended to those provided to
  7. * the wrapper.
  8. *
  9. * @private
  10. * @param {Function} func The function to partially apply arguments to.
  11. * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
  12. * @param {*} thisArg The `this` binding of `func`.
  13. * @param {Array} partials The arguments to prepend to those provided to the new function.
  14. * @returns {Function} Returns the new bound function.
  15. */
  16. function createPartialWrapper(func, bitmask, thisArg, partials) {
  17. var isBind = bitmask & BIND_FLAG,
  18. Ctor = createCtorWrapper(func);
  19. function wrapper() {
  20. // Avoid `arguments` object use disqualifying optimizations by
  21. // converting it to an array before providing it `func`.
  22. var argsIndex = -1,
  23. argsLength = arguments.length,
  24. leftIndex = -1,
  25. leftLength = partials.length,
  26. args = Array(leftLength + argsLength);
  27. while (++leftIndex < leftLength) {
  28. args[leftIndex] = partials[leftIndex];
  29. }
  30. while (argsLength--) {
  31. args[leftIndex++] = arguments[++argsIndex];
  32. }
  33. var fn = (this && this !== global && this instanceof wrapper) ? Ctor : func;
  34. return fn.apply(isBind ? thisArg : this, args);
  35. }
  36. return wrapper;
  37. }
  38. module.exports = createPartialWrapper;