partial.js 977 B

123456789101112131415161718192021222324
  1. import restArguments from './restArguments.js';
  2. import executeBound from './_executeBound.js';
  3. import _ from './underscore.js';
  4. // Partially apply a function by creating a version that has had some of its
  5. // arguments pre-filled, without changing its dynamic `this` context. `_` acts
  6. // as a placeholder by default, allowing any combination of arguments to be
  7. // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
  8. var partial = restArguments(function(func, boundArgs) {
  9. var placeholder = partial.placeholder;
  10. var bound = function() {
  11. var position = 0, length = boundArgs.length;
  12. var args = Array(length);
  13. for (var i = 0; i < length; i++) {
  14. args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
  15. }
  16. while (position < arguments.length) args.push(arguments[position++]);
  17. return executeBound(func, bound, this, this, args);
  18. };
  19. return bound;
  20. });
  21. partial.placeholder = _;
  22. export default partial;