collection-from.js 1.0 KB

12345678910111213141516171819202122232425262728293031
  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 isNullOrUndefined = require('../internals/is-null-or-undefined');
  8. var iterate = require('../internals/iterate');
  9. var push = [].push;
  10. module.exports = function from(source /* , mapFn, thisArg */) {
  11. var length = arguments.length;
  12. var mapFn = length > 1 ? arguments[1] : undefined;
  13. var mapping, array, n, boundFunction;
  14. aConstructor(this);
  15. mapping = mapFn !== undefined;
  16. if (mapping) aCallable(mapFn);
  17. if (isNullOrUndefined(source)) return new this();
  18. array = [];
  19. if (mapping) {
  20. n = 0;
  21. boundFunction = bind(mapFn, length > 2 ? arguments[2] : undefined);
  22. iterate(source, function (nextItem) {
  23. call(push, array, boundFunction(nextItem, n++));
  24. });
  25. } else {
  26. iterate(source, push, { that: array });
  27. }
  28. return new this(array);
  29. };