_createPartial.js 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var apply = require('./_apply'),
  2. createCtor = require('./_createCtor'),
  3. root = require('./_root');
  4. /** Used to compose bitmasks for function metadata. */
  5. var WRAP_BIND_FLAG = 1;
  6. /**
  7. * Creates a function that wraps `func` to invoke it with the `this` binding
  8. * of `thisArg` and `partials` prepended to the arguments it receives.
  9. *
  10. * @private
  11. * @param {Function} func The function to wrap.
  12. * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
  13. * @param {*} thisArg The `this` binding of `func`.
  14. * @param {Array} partials The arguments to prepend to those provided to
  15. * the new function.
  16. * @returns {Function} Returns the new wrapped function.
  17. */
  18. function createPartial(func, bitmask, thisArg, partials) {
  19. var isBind = bitmask & WRAP_BIND_FLAG,
  20. Ctor = createCtor(func);
  21. function wrapper() {
  22. var argsIndex = -1,
  23. argsLength = arguments.length,
  24. leftIndex = -1,
  25. leftLength = partials.length,
  26. args = Array(leftLength + argsLength),
  27. fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
  28. while (++leftIndex < leftLength) {
  29. args[leftIndex] = partials[leftIndex];
  30. }
  31. while (argsLength--) {
  32. args[leftIndex++] = arguments[++argsIndex];
  33. }
  34. return apply(fn, isBind ? thisArg : this, args);
  35. }
  36. return wrapper;
  37. }
  38. module.exports = createPartial;