_baseFlatten.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. var arrayPush = require('./_arrayPush'),
  2. isFlattenable = require('./_isFlattenable');
  3. /**
  4. * The base implementation of `_.flatten` with support for restricting flattening.
  5. *
  6. * @private
  7. * @param {Array} array The array to flatten.
  8. * @param {number} depth The maximum recursion depth.
  9. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
  10. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
  11. * @param {Array} [result=[]] The initial result value.
  12. * @returns {Array} Returns the new flattened array.
  13. */
  14. function baseFlatten(array, depth, predicate, isStrict, result) {
  15. var index = -1,
  16. length = array.length;
  17. predicate || (predicate = isFlattenable);
  18. result || (result = []);
  19. while (++index < length) {
  20. var value = array[index];
  21. if (depth > 0 && predicate(value)) {
  22. if (depth > 1) {
  23. // Recursively flatten arrays (susceptible to call stack limits).
  24. baseFlatten(value, depth - 1, predicate, isStrict, result);
  25. } else {
  26. arrayPush(result, value);
  27. }
  28. } else if (!isStrict) {
  29. result[result.length] = value;
  30. }
  31. }
  32. return result;
  33. }
  34. module.exports = baseFlatten;