You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = global || self, global.flatten = factory());
  5. }(this, (function () { 'use strict';
  6. var shallowProperty = key => obj => obj == null ? void 0 : obj[key];
  7. var getLength = shallowProperty('length');
  8. const MAX_ARRAY_INDEX = 2 ** 53 - 1;
  9. var isArrayLike = (collection) => {
  10. const length = getLength(collection);
  11. return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
  12. };
  13. var isArguments = obj => toString.call(obj) === '[object Arguments]';
  14. var isObject = obj => {
  15. const type = typeof obj;
  16. return type === 'function' || type === 'object' && !!obj;
  17. };
  18. var getKeys = (obj) => {
  19. if (!isObject(obj)) return [];
  20. return Object.keys(obj);
  21. };
  22. var optimizeCb = (func, context, argCount) => {
  23. if (context === void 0) return func;
  24. switch (argCount == null ? 3 : argCount) {
  25. case 1: return value => func.call(context, value);
  26. // The 2-argument case is omitted because we’re not using it.
  27. case 3: return (value, index, collection) => func.call(context, value, index, collection);
  28. case 4: return (accumulator, value, index, collection) => func.call(context, accumulator, value, index, collection);
  29. }
  30. return (...args) => func.apply(context, args);
  31. };
  32. var forEach = (obj, iteratee, context) => {
  33. iteratee = optimizeCb(iteratee, context);
  34. if (isArrayLike(obj)) {
  35. let i = 0;
  36. for (const item of obj) {
  37. iteratee(item, i++, obj);
  38. }
  39. } else {
  40. const keys = getKeys(obj);
  41. for (const key of keys) {
  42. iteratee(obj[key], key, obj);
  43. }
  44. }
  45. return obj;
  46. };
  47. const flatten = (input, shallow, strict, output = []) => {
  48. let idx = output.length;
  49. forEach(input, value => {
  50. if (isArrayLike(value) && (Array.isArray(value) || isArguments(value))) {
  51. if (shallow) {
  52. let j = 0;
  53. const len = value.length;
  54. while (j < len) output[idx++] = value[j++];
  55. } else {
  56. flatten(value, shallow, strict, output);
  57. idx = output.length;
  58. }
  59. } else if (!strict) {
  60. output[idx++] = value;
  61. }
  62. });
  63. return output;
  64. };
  65. var flatten_1 = (array, shallow) => flatten(array, shallow, false);
  66. var flatUtil = flatten_1;
  67. return flatUtil;
  68. })));