toArray.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. var Symbol = require('./_Symbol'),
  2. copyArray = require('./_copyArray'),
  3. getTag = require('./_getTag'),
  4. isArrayLike = require('./isArrayLike'),
  5. isString = require('./isString'),
  6. iteratorToArray = require('./_iteratorToArray'),
  7. mapToArray = require('./_mapToArray'),
  8. setToArray = require('./_setToArray'),
  9. stringToArray = require('./_stringToArray'),
  10. values = require('./values');
  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. module.exports = toArray;