tools/utils/src/modules/any-any.js

  1. /**
  2. * @module @svizzle/utils/any-any
  3. */
  4. import * as _ from 'lamb';
  5. import {isValidNumber} from './any-boolean.js';
  6. /**
  7. * Return an empty array if the input is undefined or identity otherwise.
  8. *
  9. * @function
  10. * @arg {*} any
  11. * @return {(*|array)}
  12. *
  13. * @example
  14. > makeEmptyArrayIfUndefined(undefined)
  15. []
  16. > makeEmptyArrayIfUndefined([1, 2, 3])
  17. [1, 2, 3]
  18. > makeEmptyArrayIfUndefined({a: 1})
  19. {a: 1}
  20. > makeEmptyArrayIfUndefined('a')
  21. 'a'
  22. *
  23. * @since 0.1.0
  24. */
  25. export const makeEmptyArrayIfUndefined = x => _.isUndefined(x) ? [] : x;
  26. /**
  27. * Return a number if the input can be converted to float, identity otherwise
  28. *
  29. * @function
  30. * @arg {*} any
  31. * @return {number|*}
  32. *
  33. * @example
  34. > toFloatOrIdentity('2')
  35. 2
  36. > toFloatOrIdentity('2px')
  37. 2
  38. > toFloatOrIdentity('')
  39. ''
  40. > toFloatOrIdentity('h2o')
  41. 'h2o'
  42. > toFloatOrIdentity([1.1])
  43. 1.1
  44. > toFloatOrIdentity([1.1, 2])
  45. 1.1
  46. > toFloatOrIdentity([1.1, 2, 3])
  47. 1.1
  48. > toFloatOrIdentity([])
  49. []
  50. > toFloatOrIdentity({a: 1})
  51. {a: 1}
  52. > toFloatOrIdentity(true)
  53. true
  54. > toFloatOrIdentity(null)
  55. null
  56. > toFloatOrIdentity(undefined)
  57. undefined
  58. * @since 0.1.0
  59. */
  60. export const toFloatOrIdentity = x => {
  61. const parsed = parseFloat(x);
  62. return isValidNumber(parsed) ? parsed : x;
  63. };
  64. /**
  65. * Return a copy of the input after stringifying it and parsing it.
  66. * This can be useful to check equality of json variables with json objects
  67. * obtained from a file, because e.g. stringifying strips `undefined` values.
  68. *
  69. * @function
  70. * @arg {*} any
  71. * @return {*} any
  72. *
  73. * @example
  74. *
  75. > actual = {a: 1, b: undefined}
  76. {a: 1, b: undefined}
  77. >
  78. > // note how `JSON.stringify` works
  79. > JSON.stringify(actual)
  80. '{"a":1}'
  81. >
  82. > expectedFromFile = {a: 1}
  83. > assert.deepStrictEqual(actual, expectedFromFile)
  84. Uncaught AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  85. + actual - expected
  86. {
  87. a: 1,
  88. + b: undefined
  89. }
  90. >
  91. > sanitizedObj = sanitize(actual)
  92. > assert.deepStrictEqual(sanitizedObj, expectedFromFile)
  93. undefined
  94. > array = [1, undefined]
  95. > sanitize(array)
  96. [1, null]
  97. *
  98. * @since 0.17.0
  99. */
  100. export const sanitize = _.pipe([JSON.stringify, JSON.parse]);