bindCallback.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var identity = require('../utility/identity');
  2. /**
  3. * A specialized version of `baseCallback` which only supports `this` binding
  4. * and specifying the number of arguments to provide to `func`.
  5. *
  6. * @private
  7. * @param {Function} func The function to bind.
  8. * @param {*} thisArg The `this` binding of `func`.
  9. * @param {number} [argCount] The number of arguments to provide to `func`.
  10. * @returns {Function} Returns the callback.
  11. */
  12. function bindCallback(func, thisArg, argCount) {
  13. if (typeof func != 'function') {
  14. return identity;
  15. }
  16. if (thisArg === undefined) {
  17. return func;
  18. }
  19. switch (argCount) {
  20. case 1: return function(value) {
  21. return func.call(thisArg, value);
  22. };
  23. case 3: return function(value, index, collection) {
  24. return func.call(thisArg, value, index, collection);
  25. };
  26. case 4: return function(accumulator, value, index, collection) {
  27. return func.call(thisArg, accumulator, value, index, collection);
  28. };
  29. case 5: return function(value, other, key, object, source) {
  30. return func.call(thisArg, value, other, key, object, source);
  31. };
  32. }
  33. return function() {
  34. return func.apply(thisArg, arguments);
  35. };
  36. }
  37. module.exports = bindCallback;