arrayFrom.js.flow 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // @flow strict
  2. import { SYMBOL_ITERATOR } from './symbols';
  3. declare function arrayFrom<T>(arrayLike: Iterable<T>): Array<T>;
  4. // eslint-disable-next-line no-redeclare
  5. declare function arrayFrom<T: mixed>(
  6. arrayLike: mixed,
  7. mapFn?: (elem: mixed, index: number) => T,
  8. thisArg?: mixed,
  9. ): Array<T>;
  10. /* eslint-disable no-redeclare */
  11. // $FlowFixMe[name-already-bound]
  12. const arrayFrom =
  13. Array.from ||
  14. function (obj, mapFn, thisArg) {
  15. if (obj == null) {
  16. throw new TypeError(
  17. 'Array.from requires an array-like object - not null or undefined',
  18. );
  19. }
  20. // Is Iterable?
  21. const iteratorMethod = obj[SYMBOL_ITERATOR];
  22. if (typeof iteratorMethod === 'function') {
  23. const iterator = iteratorMethod.call(obj);
  24. const result = [];
  25. let step;
  26. for (let i = 0; !(step = iterator.next()).done; ++i) {
  27. result.push(mapFn.call(thisArg, step.value, i));
  28. // Infinite Iterators could cause forEach to run forever.
  29. // After a very large number of iterations, produce an error.
  30. // istanbul ignore if (Too big to actually test)
  31. if (i > 9999999) {
  32. throw new TypeError('Near-infinite iteration.');
  33. }
  34. }
  35. return result;
  36. }
  37. // Is Array like?
  38. const length = obj.length;
  39. if (typeof length === 'number' && length >= 0 && length % 1 === 0) {
  40. const result = [];
  41. for (let i = 0; i < length; ++i) {
  42. if (Object.prototype.hasOwnProperty.call(obj, i)) {
  43. result.push(mapFn.call(thisArg, obj[i], i));
  44. }
  45. }
  46. return result;
  47. }
  48. return [];
  49. };
  50. export default arrayFrom;