You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.9 KiB

4 years ago
  1. /**
  2. * Helper function to set an immutable property
  3. * @param {Object} source - object where the new property will be set
  4. * @param {string} key - object key where the new property will be stored
  5. * @param {*} value - value of the new property
  6. * @param {Object} options - set the propery overriding the default options
  7. * @returns {Object} - the original object modified
  8. */
  9. export function defineProperty(source, key, value, options = {}) {
  10. /* eslint-disable fp/no-mutating-methods */
  11. Object.defineProperty(source, key, {
  12. value,
  13. enumerable: false,
  14. writable: false,
  15. configurable: true,
  16. ...options
  17. })
  18. /* eslint-enable fp/no-mutating-methods */
  19. return source
  20. }
  21. /**
  22. * Define multiple properties on a target object
  23. * @param {Object} source - object where the new properties will be set
  24. * @param {Object} properties - object containing as key pair the key + value properties
  25. * @param {Object} options - set the propery overriding the default options
  26. * @returns {Object} the original object modified
  27. */
  28. export function defineProperties(source, properties, options) {
  29. Object.entries(properties).forEach(([key, value]) => {
  30. defineProperty(source, key, value, options)
  31. })
  32. return source
  33. }
  34. /**
  35. * Define default properties if they don't exist on the source object
  36. * @param {Object} source - object that will receive the default properties
  37. * @param {Object} defaults - object containing additional optional keys
  38. * @returns {Object} the original object received enhanced
  39. */
  40. export function defineDefaults(source, defaults) {
  41. Object.entries(defaults).forEach(([key, value]) => {
  42. if (!source[key]) source[key] = value
  43. })
  44. return source
  45. }
  46. /**
  47. * Simple clone deep function, do not use it for classes or recursive objects!
  48. * @param {*} source - possibily an object to clone
  49. * @returns {*} the object we wanted to clone
  50. */
  51. export function cloneDeep(source) {
  52. return JSON.parse(JSON.stringify(source))
  53. }