collection-from.js 982 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. // https://tc39.github.io/proposal-setmap-offrom/
  3. var bind = require('../internals/function-bind-context');
  4. var call = require('../internals/function-call');
  5. var aCallable = require('../internals/a-callable');
  6. var aConstructor = require('../internals/a-constructor');
  7. var iterate = require('../internals/iterate');
  8. var push = [].push;
  9. module.exports = function from(source /* , mapFn, thisArg */) {
  10. var length = arguments.length;
  11. var mapFn = length > 1 ? arguments[1] : undefined;
  12. var mapping, array, n, boundFunction;
  13. aConstructor(this);
  14. mapping = mapFn !== undefined;
  15. if (mapping) aCallable(mapFn);
  16. if (source == undefined) return new this();
  17. array = [];
  18. if (mapping) {
  19. n = 0;
  20. boundFunction = bind(mapFn, length > 2 ? arguments[2] : undefined);
  21. iterate(source, function (nextItem) {
  22. call(push, array, boundFunction(nextItem, n++));
  23. });
  24. } else {
  25. iterate(source, push, { that: array });
  26. }
  27. return new this(array);
  28. };