collection-from.js 852 B

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