cast.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * Module to convert values between various JavaScript types.
  3. * @module
  4. * @private
  5. */
  6. /**
  7. * Check whether a string contains a boolean or numeric value, and convert the string to the
  8. * appropriate type if necessary.
  9. *
  10. * @private
  11. * @param {string} str - The string to convert.
  12. * @return {(string|number|boolean)} The converted value.
  13. */
  14. function castString(str) {
  15. let number;
  16. let result;
  17. switch (str) {
  18. case 'true':
  19. result = true;
  20. break;
  21. case 'false':
  22. result = false;
  23. break;
  24. case 'NaN':
  25. result = NaN;
  26. break;
  27. case 'null':
  28. result = null;
  29. break;
  30. case 'undefined':
  31. result = undefined;
  32. break;
  33. default:
  34. if (typeof str === 'string') {
  35. if (str.includes('.')) {
  36. number = parseFloat(str);
  37. }
  38. else {
  39. number = parseInt(str, 10);
  40. }
  41. if ( String(number) === str && !isNaN(number) ) {
  42. result = number;
  43. }
  44. else {
  45. result = str;
  46. }
  47. }
  48. }
  49. return result;
  50. }
  51. /**
  52. * Check whether a string contains a boolean or numeric value, and convert the string to the
  53. * appropriate type if necessary.
  54. *
  55. * If an object or array is passed to this method, the object or array's values will be recursively
  56. * converted to the appropriate types. The original object or array is not modified.
  57. *
  58. * @private
  59. * @param {(string|Object|Array)} item - The item whose type will be converted.
  60. * @return {(string|number|boolean|Object|Array)} The converted value.
  61. */
  62. exports.cast = function cast(item) {
  63. let result;
  64. if ( Array.isArray(item) ) {
  65. result = [];
  66. for (let i = 0, l = item.length; i < l; i++) {
  67. result[i] = cast(item[i]);
  68. }
  69. }
  70. else if (typeof item === 'object' && item !== null) {
  71. result = {};
  72. Object.keys(item).forEach(prop => {
  73. result[prop] = cast(item[prop]);
  74. });
  75. }
  76. else if (typeof item === 'string') {
  77. result = castString(item);
  78. }
  79. else {
  80. result = item;
  81. }
  82. return result;
  83. };