toArray.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import Symbol from './_Symbol.js';
  2. import copyArray from './_copyArray.js';
  3. import getTag from './_getTag.js';
  4. import isArrayLike from './isArrayLike.js';
  5. import isString from './isString.js';
  6. import iteratorToArray from './_iteratorToArray.js';
  7. import mapToArray from './_mapToArray.js';
  8. import setToArray from './_setToArray.js';
  9. import stringToArray from './_stringToArray.js';
  10. import values from './values.js';
  11. /** `Object#toString` result references. */
  12. var mapTag = '[object Map]',
  13. setTag = '[object Set]';
  14. /** Built-in value references. */
  15. var symIterator = Symbol ? Symbol.iterator : undefined;
  16. /**
  17. * Converts `value` to an array.
  18. *
  19. * @static
  20. * @since 0.1.0
  21. * @memberOf _
  22. * @category Lang
  23. * @param {*} value The value to convert.
  24. * @returns {Array} Returns the converted array.
  25. * @example
  26. *
  27. * _.toArray({ 'a': 1, 'b': 2 });
  28. * // => [1, 2]
  29. *
  30. * _.toArray('abc');
  31. * // => ['a', 'b', 'c']
  32. *
  33. * _.toArray(1);
  34. * // => []
  35. *
  36. * _.toArray(null);
  37. * // => []
  38. */
  39. function toArray(value) {
  40. if (!value) {
  41. return [];
  42. }
  43. if (isArrayLike(value)) {
  44. return isString(value) ? stringToArray(value) : copyArray(value);
  45. }
  46. if (symIterator && value[symIterator]) {
  47. return iteratorToArray(value[symIterator]());
  48. }
  49. var tag = getTag(value),
  50. func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
  51. return func(value);
  52. }
  53. export default toArray;