setDefaultOptions.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import {
  2. getDefaultOptions,
  3. setDefaultOptions as setInternalDefaultOptions,
  4. } from "./_lib/defaultOptions.js";
  5. /**
  6. * @name setDefaultOptions
  7. * @category Common Helpers
  8. * @summary Set default options including locale.
  9. * @pure false
  10. *
  11. * @description
  12. * Sets the defaults for
  13. * `options.locale`, `options.weekStartsOn` and `options.firstWeekContainsDate`
  14. * arguments for all functions.
  15. *
  16. * @param options - An object with options
  17. *
  18. * @example
  19. * // Set global locale:
  20. * import { es } from 'date-fns/locale'
  21. * setDefaultOptions({ locale: es })
  22. * const result = format(new Date(2014, 8, 2), 'PPPP')
  23. * //=> 'martes, 2 de septiembre de 2014'
  24. *
  25. * @example
  26. * // Start of the week for 2 September 2014:
  27. * const result = startOfWeek(new Date(2014, 8, 2))
  28. * //=> Sun Aug 31 2014 00:00:00
  29. *
  30. * @example
  31. * // Start of the week for 2 September 2014,
  32. * // when we set that week starts on Monday by default:
  33. * setDefaultOptions({ weekStartsOn: 1 })
  34. * const result = startOfWeek(new Date(2014, 8, 2))
  35. * //=> Mon Sep 01 2014 00:00:00
  36. *
  37. * @example
  38. * // Manually set options take priority over default options:
  39. * setDefaultOptions({ weekStartsOn: 1 })
  40. * const result = startOfWeek(new Date(2014, 8, 2), { weekStartsOn: 0 })
  41. * //=> Sun Aug 31 2014 00:00:00
  42. *
  43. * @example
  44. * // Remove the option by setting it to `undefined`:
  45. * setDefaultOptions({ weekStartsOn: 1 })
  46. * setDefaultOptions({ weekStartsOn: undefined })
  47. * const result = startOfWeek(new Date(2014, 8, 2))
  48. * //=> Sun Aug 31 2014 00:00:00
  49. */
  50. export function setDefaultOptions(options) {
  51. const result = {};
  52. const defaultOptions = getDefaultOptions();
  53. for (const property in defaultOptions) {
  54. if (Object.prototype.hasOwnProperty.call(defaultOptions, property)) {
  55. // [TODO] I challenge you to fix the type
  56. result[property] = defaultOptions[property];
  57. }
  58. }
  59. for (const property in options) {
  60. if (Object.prototype.hasOwnProperty.call(options, property)) {
  61. if (options[property] === undefined) {
  62. // [TODO] I challenge you to fix the type
  63. delete result[property];
  64. } else {
  65. // [TODO] I challenge you to fix the type
  66. result[property] = options[property];
  67. }
  68. }
  69. }
  70. setInternalDefaultOptions(result);
  71. }
  72. // Fallback for modularized imports:
  73. export default setDefaultOptions;