atomic-fns 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (216) hide show
  1. package/README.md +397 -91
  2. package/dist/array/index.d.ts +9 -0
  3. package/dist/array/index.js +9 -0
  4. package/dist/array/list.d.ts +99 -0
  5. package/dist/array/list.js +133 -0
  6. package/dist/array/sets.d.ts +130 -0
  7. package/dist/array/sets.js +213 -0
  8. package/dist/async/index.d.ts +6 -0
  9. package/dist/async/index.js +6 -0
  10. package/dist/async/retry.d.ts +38 -0
  11. package/dist/async/retry.js +56 -0
  12. package/dist/async/sleep.d.ts +42 -0
  13. package/dist/async/sleep.js +76 -0
  14. package/dist/collections/bisect.d.ts +103 -0
  15. package/dist/collections/bisect.js +157 -0
  16. package/dist/collections/deque.d.ts +67 -97
  17. package/dist/collections/deque.js +197 -256
  18. package/dist/collections/entries.d.ts +89 -0
  19. package/dist/collections/entries.js +131 -0
  20. package/dist/collections/frozen-set.d.ts +42 -0
  21. package/dist/collections/frozen-set.js +64 -0
  22. package/dist/collections/group.d.ts +141 -0
  23. package/dist/collections/group.js +241 -0
  24. package/dist/collections/heap.d.ts +64 -0
  25. package/dist/collections/heap.js +205 -0
  26. package/dist/collections/index.d.ts +15 -623
  27. package/dist/collections/index.js +14 -844
  28. package/dist/collections/internal/arrayKeys.d.ts +19 -0
  29. package/dist/collections/internal/arrayKeys.js +83 -0
  30. package/dist/collections/internal/invariants.d.ts +4 -0
  31. package/dist/collections/internal/invariants.js +12 -0
  32. package/dist/collections/internal/iterable.d.ts +25 -0
  33. package/dist/collections/internal/iterable.js +62 -0
  34. package/dist/collections/iterate.d.ts +162 -0
  35. package/dist/collections/iterate.js +188 -0
  36. package/dist/collections/lru-cache.d.ts +58 -0
  37. package/dist/collections/lru-cache.js +164 -0
  38. package/dist/collections/order.d.ts +19 -0
  39. package/dist/collections/order.js +38 -0
  40. package/dist/collections/shape.d.ts +32 -0
  41. package/dist/collections/shape.js +86 -0
  42. package/dist/collections/sorted-map.d.ts +171 -0
  43. package/dist/collections/sorted-map.js +845 -0
  44. package/dist/collections/sorted-set.d.ts +103 -0
  45. package/dist/collections/sorted-set.js +147 -0
  46. package/dist/collections/splay-tree.d.ts +82 -0
  47. package/dist/collections/splay-tree.js +354 -0
  48. package/dist/collections/trie.d.ts +58 -0
  49. package/dist/collections/trie.js +196 -0
  50. package/dist/decimal/currency.d.ts +211 -0
  51. package/dist/decimal/currency.js +321 -0
  52. package/dist/decimal/decimal.d.ts +299 -0
  53. package/dist/decimal/decimal.js +660 -0
  54. package/dist/decimal/index.d.ts +11 -148
  55. package/dist/decimal/index.js +10 -410
  56. package/dist/decimal/internal/bits.d.ts +2 -0
  57. package/dist/decimal/internal/bits.js +7 -0
  58. package/dist/decimal/internal/echo.d.ts +4 -0
  59. package/dist/decimal/internal/echo.js +6 -0
  60. package/dist/decimal/internal/isqrt.d.ts +9 -0
  61. package/dist/decimal/internal/isqrt.js +34 -0
  62. package/dist/decimal/internal/locale.d.ts +7 -0
  63. package/dist/decimal/internal/locale.js +24 -0
  64. package/dist/decimal/internal/minor-units.d.ts +2 -0
  65. package/dist/decimal/internal/minor-units.js +33 -0
  66. package/dist/decimal/internal/pow10.d.ts +24 -0
  67. package/dist/decimal/internal/pow10.js +96 -0
  68. package/dist/encoding/base64.d.ts +39 -0
  69. package/dist/encoding/base64.js +53 -0
  70. package/dist/encoding/hex.d.ts +23 -0
  71. package/dist/encoding/hex.js +34 -0
  72. package/dist/encoding/index.d.ts +6 -0
  73. package/dist/encoding/index.js +6 -0
  74. package/dist/function/debounce.d.ts +68 -0
  75. package/dist/function/debounce.js +203 -0
  76. package/dist/function/index.d.ts +6 -0
  77. package/dist/function/index.js +6 -0
  78. package/dist/function/shared.d.ts +2 -0
  79. package/dist/function/shared.js +5 -0
  80. package/dist/function/wrap.d.ts +130 -0
  81. package/dist/function/wrap.js +113 -0
  82. package/dist/hash/digest.d.ts +18 -0
  83. package/dist/hash/digest.js +26 -0
  84. package/dist/hash/hash.d.ts +22 -0
  85. package/dist/hash/hash.js +252 -0
  86. package/dist/hash/hashString.d.ts +13 -0
  87. package/dist/hash/hashString.js +53 -0
  88. package/dist/hash/index.d.ts +8 -0
  89. package/dist/hash/index.js +8 -0
  90. package/dist/hash/stableStringify.d.ts +19 -0
  91. package/dist/hash/stableStringify.js +102 -0
  92. package/dist/id/index.d.ts +7 -0
  93. package/dist/id/index.js +7 -0
  94. package/dist/id/nanoid.d.ts +16 -0
  95. package/dist/id/nanoid.js +65 -0
  96. package/dist/id/uniqueId.d.ts +14 -0
  97. package/dist/id/uniqueId.js +20 -0
  98. package/dist/id/uuid.d.ts +25 -0
  99. package/dist/id/uuid.js +64 -0
  100. package/dist/index.d.ts +15 -8
  101. package/dist/index.js +15 -8
  102. package/dist/internal/bytes.d.ts +11 -0
  103. package/dist/internal/bytes.js +33 -0
  104. package/dist/internal/codec.d.ts +11 -0
  105. package/dist/internal/codec.js +84 -0
  106. package/dist/internal/compare.d.ts +10 -0
  107. package/dist/internal/compare.js +26 -0
  108. package/dist/internal/crypto.d.ts +5 -0
  109. package/dist/internal/crypto.js +11 -0
  110. package/dist/internal/keys.d.ts +12 -0
  111. package/dist/internal/keys.js +23 -0
  112. package/dist/internal/kind.d.ts +44 -0
  113. package/dist/internal/kind.js +139 -0
  114. package/dist/internal/sparse.d.ts +51 -0
  115. package/dist/internal/sparse.js +104 -0
  116. package/dist/internal/text.d.ts +7 -0
  117. package/dist/internal/text.js +15 -0
  118. package/dist/internal/timer.d.ts +10 -0
  119. package/dist/internal/timer.js +17 -0
  120. package/dist/internal/truncate.d.ts +10 -0
  121. package/dist/internal/truncate.js +22 -0
  122. package/dist/internal/walk.d.ts +47 -0
  123. package/dist/internal/walk.js +100 -0
  124. package/dist/is/index.d.ts +8 -0
  125. package/dist/is/index.js +8 -0
  126. package/dist/is/isArrayLike.d.ts +18 -0
  127. package/dist/is/isArrayLike.js +25 -0
  128. package/dist/is/isError.d.ts +13 -0
  129. package/dist/is/isError.js +18 -0
  130. package/dist/is/isNil.d.ts +12 -0
  131. package/dist/is/isNil.js +14 -0
  132. package/dist/is/isPlainObject.d.ts +15 -0
  133. package/dist/is/isPlainObject.js +34 -0
  134. package/dist/number/index.d.ts +7 -0
  135. package/dist/number/index.js +7 -0
  136. package/dist/number/round.d.ts +86 -0
  137. package/dist/number/round.js +130 -0
  138. package/dist/number/stats.d.ts +52 -0
  139. package/dist/number/stats.js +115 -0
  140. package/dist/object/cloneDeep.d.ts +28 -0
  141. package/dist/object/cloneDeep.js +200 -0
  142. package/dist/object/index.d.ts +14 -0
  143. package/dist/object/index.js +13 -0
  144. package/dist/object/isEqual.d.ts +64 -0
  145. package/dist/object/isEqual.js +289 -0
  146. package/dist/object/matches.d.ts +40 -0
  147. package/dist/object/matches.js +284 -0
  148. package/dist/object/merge.d.ts +66 -0
  149. package/dist/object/merge.js +272 -0
  150. package/dist/object/parsePath.d.ts +22 -0
  151. package/dist/object/parsePath.js +111 -0
  152. package/dist/object/path.d.ts +85 -0
  153. package/dist/object/path.js +208 -0
  154. package/dist/object/pick.d.ts +91 -0
  155. package/dist/object/pick.js +180 -0
  156. package/dist/object/reshape.d.ts +73 -0
  157. package/dist/object/reshape.js +144 -0
  158. package/dist/random/index.d.ts +96 -32
  159. package/dist/random/index.js +215 -53
  160. package/dist/string/case.d.ts +71 -0
  161. package/dist/string/case.js +152 -0
  162. package/dist/string/fold.d.ts +35 -0
  163. package/dist/string/fold.js +100 -0
  164. package/dist/string/index.d.ts +6 -187
  165. package/dist/string/index.js +6 -224
  166. package/dist/string/truncate.d.ts +25 -0
  167. package/dist/string/truncate.js +44 -0
  168. package/dist/string/words.d.ts +27 -0
  169. package/dist/string/words.js +241 -0
  170. package/package.json +99 -51
  171. package/dist/collections/BTree.d.ts +0 -230
  172. package/dist/collections/BTree.js +0 -1143
  173. package/dist/collections/Heap.d.ts +0 -69
  174. package/dist/collections/Heap.js +0 -181
  175. package/dist/collections/LRUCache.d.ts +0 -83
  176. package/dist/collections/LRUCache.js +0 -139
  177. package/dist/collections/SortedMap.d.ts +0 -92
  178. package/dist/collections/SortedMap.js +0 -131
  179. package/dist/collections/SortedSet.d.ts +0 -69
  180. package/dist/collections/SortedSet.js +0 -99
  181. package/dist/collections/SortedTree.d.ts +0 -103
  182. package/dist/collections/SortedTree.js +0 -142
  183. package/dist/collections/SplayTree.d.ts +0 -107
  184. package/dist/collections/SplayTree.js +0 -351
  185. package/dist/collections/Trie.d.ts +0 -42
  186. package/dist/collections/Trie.js +0 -104
  187. package/dist/collections/abc.d.ts +0 -152
  188. package/dist/collections/abc.js +0 -39
  189. package/dist/collections/frozenset.d.ts +0 -19
  190. package/dist/collections/frozenset.js +0 -33
  191. package/dist/functools/index.d.ts +0 -106
  192. package/dist/functools/index.js +0 -203
  193. package/dist/globals/index.d.ts +0 -268
  194. package/dist/globals/index.js +0 -447
  195. package/dist/i18n/currency.d.ts +0 -27
  196. package/dist/i18n/currency.js +0 -100
  197. package/dist/i18n/date/index.d.ts +0 -210
  198. package/dist/i18n/date/index.js +0 -552
  199. package/dist/i18n/date/utils.d.ts +0 -64
  200. package/dist/i18n/date/utils.js +0 -192
  201. package/dist/i18n/duration.d.ts +0 -113
  202. package/dist/i18n/duration.js +0 -398
  203. package/dist/i18n/format.d.ts +0 -34
  204. package/dist/i18n/format.js +0 -378
  205. package/dist/i18n/index.d.ts +0 -9
  206. package/dist/i18n/index.js +0 -8
  207. package/dist/itertools/index.d.ts +0 -251
  208. package/dist/itertools/index.js +0 -434
  209. package/dist/math/index.d.ts +0 -79
  210. package/dist/math/index.js +0 -81
  211. package/dist/mod.d.ts +0 -1
  212. package/dist/mod.js +0 -1
  213. package/dist/operators/index.d.ts +0 -148
  214. package/dist/operators/index.js +0 -325
  215. package/dist/types.d.ts +0 -19
  216. package/dist/types.js +0 -1
@@ -1,192 +0,0 @@
1
- import { asDate } from '../format.js';
2
- /**
3
- * Returns x % n but takes the sign of n instead of x
4
- * @param x
5
- * @param n
6
- * @returns {number}
7
- */
8
- function floorMod(x, n) {
9
- return x - n * Math.floor(x / n);
10
- }
11
- function parseFloating(str) {
12
- if (str != null && str !== '')
13
- return parseFloat(str);
14
- }
15
- function parseMilliseconds(str) {
16
- if (str != null && str !== '') {
17
- const f = parseFloat(`0.${str}`) * 1000;
18
- return Math.floor(f);
19
- }
20
- }
21
- export function minDate(...dates) {
22
- let ans = dates[0];
23
- if (Array.isArray(ans)) {
24
- dates = ans;
25
- ans = ans[0];
26
- }
27
- for (let i = 1; i < dates.length; i++) {
28
- if (dates[i].valueOf() < ans.valueOf() || Number.isNaN(ans.valueOf())) {
29
- ans = dates[i];
30
- }
31
- }
32
- return ans;
33
- }
34
- export function maxDate(...dates) {
35
- let ans = dates[0];
36
- if (Array.isArray(ans)) {
37
- dates = ans;
38
- ans = ans[0];
39
- }
40
- for (let i = 1; i < dates.length; i++) {
41
- if (dates[i].valueOf() > ans.valueOf() || Number.isNaN(ans.valueOf())) {
42
- ans = dates[i];
43
- }
44
- }
45
- return ans;
46
- }
47
- /**
48
- * Returns `true` if the year is a leap year, otherwise `false`.
49
- * @param year The date year
50
- * @returns {boolean} `true` if is a leap year
51
- */
52
- export function isLeapYear(year) {
53
- return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
54
- }
55
- /**
56
- * Get the number of days in the given year.
57
- * @param year The date year
58
- * @returns {number} Number of days in year
59
- */
60
- export function daysInYear(year) {
61
- return isLeapYear(year) ? 366 : 365;
62
- }
63
- /**
64
- * Get the number of days in the given date's month and year.
65
- * @param date The specified date
66
- * @returns {number} Number of days in month
67
- */
68
- export function daysInMonth(date) {
69
- const d = asDate(date), year = d.getFullYear(), month = d.getMonth() + 1;
70
- const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12;
71
- if (modMonth === 2) {
72
- return isLeapYear(modYear) ? 29 : 28;
73
- }
74
- else {
75
- return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1];
76
- }
77
- }
78
- // COERCION
79
- export function asNumber(value) {
80
- const numericValue = Number(value);
81
- if (typeof value === 'boolean' || value === '' || Number.isNaN(numericValue))
82
- throw new Error(`Invalid unit value ${value}`);
83
- return numericValue;
84
- }
85
- const isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;
86
- function extractISODuration(match) {
87
- const [s, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match;
88
- const hasNegativePrefix = s[0] === '-';
89
- const negativeSeconds = secondStr && secondStr[0] === '-';
90
- const maybeNegate = (num, force = false) => num !== undefined && (force || (num && hasNegativePrefix)) ? -num : num;
91
- return [
92
- {
93
- years: maybeNegate(parseFloating(yearStr)),
94
- months: maybeNegate(parseFloating(monthStr)),
95
- weeks: maybeNegate(parseFloating(weekStr)),
96
- days: maybeNegate(parseFloating(dayStr)),
97
- hours: maybeNegate(parseFloating(hourStr)),
98
- minutes: maybeNegate(parseFloating(minuteStr)),
99
- seconds: maybeNegate(parseFloating(secondStr), secondStr === '-0'),
100
- milliseconds: maybeNegate(parseMilliseconds(millisecondsStr), negativeSeconds)
101
- }
102
- ];
103
- }
104
- function parse(s, ...patterns) {
105
- if (s == null) {
106
- return [null, null];
107
- }
108
- for (const [regex, extractor] of patterns) {
109
- const m = regex.exec(s);
110
- if (m) {
111
- return extractor(m);
112
- }
113
- }
114
- return [null, null];
115
- }
116
- export function parseISODuration(s) {
117
- return parse(s, [isoDuration, extractISODuration]);
118
- }
119
- function createUTCDate(...args) {
120
- let date, y = args[0];
121
- // the Date.UTC function remaps years 0-99 to 1900-1999
122
- if (y < 100 && y >= 0) {
123
- // preserve leap years using a full 400 year cycle, then reset
124
- args[0] = y + 400;
125
- date = new Date(Date.UTC.apply(null, args));
126
- if (Number.isFinite(date.getUTCFullYear())) {
127
- date.setUTCFullYear(y);
128
- }
129
- }
130
- else {
131
- date = new Date(Date.UTC.apply(null, args));
132
- }
133
- return date;
134
- }
135
- function firstWeekOffset(year, dow, doy) {
136
- var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
137
- fwd = 7 + dow - doy,
138
- // first-week day local weekday -- which local weekday is fwd
139
- fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
140
- return -fwdlw + fwd - 1;
141
- }
142
- /**
143
- * Returns the number of weeks in the specified year.
144
- * @param year
145
- * @param firstDayOfWeek
146
- * @param firstDayOfYear
147
- */
148
- export function weeksInYear(year, firstDayOfWeek = 1, firstDayOfYear = 1) {
149
- var weekOffset = firstWeekOffset(year, firstDayOfWeek, firstDayOfYear), weekOffsetNext = firstWeekOffset(year + 1, firstDayOfWeek, firstDayOfYear);
150
- return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
151
- }
152
- /**
153
- * Returns the week of the year for the specified date
154
- * @param date The date value
155
- * @param firstDayOfWeek The weekday a week starts on, where Sunday is 0
156
- * @param firstDayOfYear Picks week 1: the week holding January `7 + firstDayOfWeek - firstDayOfYear`, so `1, 4` gives ISO weeks
157
- * @returns The week and the year that week belongs to
158
- */
159
- export function weekOfYear(date, firstDayOfWeek = 1, firstDayOfYear = 1) {
160
- const year = asDate(date).getFullYear();
161
- const doy = dayOfYear(date);
162
- let weekOffset = firstWeekOffset(year, firstDayOfWeek, firstDayOfYear), week = Math.floor((doy - weekOffset - 1) / 7) + 1, resWeek, resYear;
163
- if (week < 1) {
164
- resYear = year - 1;
165
- resWeek = week + weeksInYear(resYear, firstDayOfWeek, firstDayOfYear);
166
- }
167
- else if (week > weeksInYear(year, firstDayOfWeek, firstDayOfYear)) {
168
- resWeek = week - weeksInYear(year, firstDayOfWeek, firstDayOfYear);
169
- resYear = year + 1;
170
- }
171
- else {
172
- resYear = year;
173
- resWeek = week;
174
- }
175
- return {
176
- week: resWeek,
177
- year: resYear
178
- };
179
- }
180
- export function isoWeeksInYear(year) {
181
- return weeksInYear(year, 1, 4);
182
- }
183
- export function dayOfYear(input) {
184
- input = asDate(input);
185
- input.setHours(0);
186
- input.setMinutes(0);
187
- input.setSeconds(0);
188
- input.setMilliseconds(0);
189
- const start = new Date(input);
190
- start.setMonth(0, 1);
191
- return Math.round((+input - start.getTime()) / 864e5) + 1;
192
- }
@@ -1,113 +0,0 @@
1
- export type DurationUnit = 'year' | 'years' | 'quarter' | 'quarters' | 'month' | 'months' | 'week' | 'weeks' | 'day' | 'days' | 'hour' | 'hours' | 'minute' | 'minutes' | 'second' | 'seconds' | 'millisecond' | 'milliseconds';
2
- export interface TDuration {
3
- years?: number;
4
- months?: number;
5
- weeks?: number;
6
- days?: number;
7
- hours?: number;
8
- minutes?: number;
9
- seconds?: number;
10
- milliseconds?: number;
11
- }
12
- export declare const UNITS_PLURAL: Record<DurationUnit, DurationUnit>;
13
- export declare class Duration {
14
- values: TDuration;
15
- private matrix;
16
- constructor(dur?: number | TDuration | Duration, exact?: boolean);
17
- private withValues;
18
- /** Get the years. */
19
- get years(): number;
20
- /** Get the months. */
21
- get months(): number;
22
- /** Get the weeks. */
23
- get weeks(): number;
24
- /** Get the days. */
25
- get days(): number;
26
- /** Get the hours. */
27
- get hours(): number;
28
- /** Get the minutes. */
29
- get minutes(): number;
30
- /** Get the seconds. */
31
- get seconds(): number;
32
- /** Get the milliseconds. */
33
- get milliseconds(): number;
34
- /**
35
- * Get the value of unit.
36
- * @param {string} unit - a unit such as 'minute' or 'day'
37
- * @example new Duration({years: 2, days: 3}).get('years') // 2
38
- * @example new Duration({years: 2, days: 3}).get('months') // 0
39
- * @example new Duration({years: 2, days: 3}).get('days') // 3
40
- * @return {number}
41
- */
42
- get(unit: string): number;
43
- add(duration: TDuration): Duration;
44
- /**
45
- * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
46
- * @param {Duration|Object|number} duration - The amount to subtract.
47
- * @return {Duration}
48
- */
49
- subtract(duration: Duration | TDuration | number): Duration;
50
- /**
51
- * Return the negative of this Duration.
52
- * @example
53
- ```js
54
- new Duration({ hours: 1, seconds: 30 }).negated().toObject()
55
- // { hours: -1, seconds: -30 }
56
- ```
57
- * @returns {Duration}
58
- */
59
- negated(): Duration;
60
- /**
61
- * Return the absolute values of this Duration.
62
- * @example
63
- ```js
64
- new Duration({ hours: 1, seconds: -30 }).abs().toObject()
65
- // { hours: 1, seconds: 30 }
66
- ```
67
- * @returns {Duration}
68
- */
69
- abs(): Duration;
70
- private shiftToAll;
71
- private shiftTo;
72
- total(unit: DurationUnit): number;
73
- exact(unit?: DurationUnit): number | this;
74
- toObject(): {
75
- years?: number;
76
- months?: number;
77
- weeks?: number;
78
- days?: number;
79
- hours?: number;
80
- minutes?: number;
81
- seconds?: number;
82
- milliseconds?: number;
83
- };
84
- normalize(): Duration;
85
- rescale(): Duration;
86
- /**
87
- * Returns an ISO 8601-compliant string representation of this Duration.
88
- * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
89
- * @example new Duration({ years: 3, seconds: 45 }).toString() // 'P3YT45S'
90
- * @example new Duration({ months: 4, seconds: 45 }).toString() // 'P4MT45S'
91
- * @example new Duration({ months: 5 }).toString() // 'P5M'
92
- * @example new Duration({ minutes: 5 }).toString() // 'PT5M'
93
- * @example new Duration({ milliseconds: 6 }).toString() // 'PT0.006S'
94
- * @return {string}
95
- */
96
- toISOString(): string;
97
- toString(): string;
98
- /**
99
- * Create a Duration from an ISO 8601 duration string.
100
- *
101
- * @example
102
- ```js
103
- Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject()
104
- // { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
105
- Duration.fromISO('PT23H').toObject()
106
- // { hours: 23 }
107
- Duration.fromISO('P5Y3M').toObject()
108
- // { years: 5, months: 3 }
109
- ```
110
- * @return {Duration}
111
- */
112
- static fromISO(text: string): Duration;
113
- }
@@ -1,398 +0,0 @@
1
- import { pick } from '../collections/index.js';
2
- import { isNumber, isObject, ValueError } from '../globals/index.js';
3
- import { round } from '../math/index.js';
4
- import { parseISODuration } from './date/utils.js';
5
- const lowOrderMatrix = {
6
- weeks: {
7
- days: 7,
8
- hours: 7 * 24,
9
- minutes: 7 * 24 * 60,
10
- seconds: 7 * 24 * 60 * 60,
11
- milliseconds: 7 * 24 * 60 * 60 * 1000
12
- },
13
- days: {
14
- hours: 24,
15
- minutes: 24 * 60,
16
- seconds: 24 * 60 * 60,
17
- milliseconds: 24 * 60 * 60 * 1000
18
- },
19
- hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 },
20
- minutes: { seconds: 60, milliseconds: 60 * 1000 },
21
- seconds: { milliseconds: 1000 }
22
- };
23
- const casualMatrix = {
24
- years: {
25
- quarters: 4,
26
- months: 12,
27
- weeks: 52,
28
- days: 365,
29
- hours: 365 * 24,
30
- minutes: 365 * 24 * 60,
31
- seconds: 365 * 24 * 60 * 60,
32
- milliseconds: 365 * 24 * 60 * 60 * 1000
33
- },
34
- quarters: {
35
- months: 3,
36
- weeks: 13,
37
- days: 91,
38
- hours: 91 * 24,
39
- minutes: 91 * 24 * 60,
40
- seconds: 91 * 24 * 60 * 60,
41
- milliseconds: 91 * 24 * 60 * 60 * 1000
42
- },
43
- months: {
44
- weeks: 4,
45
- days: 30,
46
- hours: 30 * 24,
47
- minutes: 30 * 24 * 60,
48
- seconds: 30 * 24 * 60 * 60,
49
- milliseconds: 30 * 24 * 60 * 60 * 1000
50
- },
51
- ...lowOrderMatrix
52
- };
53
- const exactDaysInYear = 146097.0 / 400;
54
- const exactDaysInMonth = 146097.0 / 4800;
55
- const exactMatrix = {
56
- years: {
57
- quarters: 4,
58
- months: 12,
59
- weeks: exactDaysInYear / 7,
60
- days: exactDaysInYear,
61
- hours: exactDaysInYear * 24,
62
- minutes: exactDaysInYear * 24 * 60,
63
- seconds: exactDaysInYear * 24 * 60 * 60,
64
- milliseconds: exactDaysInYear * 24 * 60 * 60 * 1000
65
- },
66
- quarters: {
67
- months: 3,
68
- weeks: exactDaysInYear / 28,
69
- days: exactDaysInYear / 4,
70
- hours: (exactDaysInYear * 24) / 4,
71
- minutes: (exactDaysInYear * 24 * 60) / 4,
72
- seconds: (exactDaysInYear * 24 * 60 * 60) / 4,
73
- milliseconds: (exactDaysInYear * 24 * 60 * 60 * 1000) / 4
74
- },
75
- months: {
76
- weeks: exactDaysInMonth / 7,
77
- days: exactDaysInMonth,
78
- hours: exactDaysInMonth * 24,
79
- minutes: exactDaysInMonth * 24 * 60,
80
- seconds: exactDaysInMonth * 24 * 60 * 60,
81
- milliseconds: exactDaysInMonth * 24 * 60 * 60 * 1000
82
- },
83
- ...lowOrderMatrix
84
- };
85
- export const UNITS_PLURAL = {
86
- year: 'years',
87
- years: 'years',
88
- quarter: 'quarters',
89
- quarters: 'quarters',
90
- month: 'months',
91
- months: 'months',
92
- week: 'weeks',
93
- weeks: 'weeks',
94
- day: 'days',
95
- days: 'days',
96
- hour: 'hours',
97
- hours: 'hours',
98
- minute: 'minutes',
99
- minutes: 'minutes',
100
- second: 'seconds',
101
- seconds: 'seconds',
102
- millisecond: 'milliseconds',
103
- milliseconds: 'milliseconds'
104
- };
105
- const orderedUnits = [
106
- 'years',
107
- 'quarters',
108
- 'months',
109
- 'weeks',
110
- 'days',
111
- 'hours',
112
- 'minutes',
113
- 'seconds',
114
- 'milliseconds'
115
- ];
116
- const reverseUnits = orderedUnits.slice(0).reverse();
117
- export class Duration {
118
- values = {};
119
- matrix = casualMatrix;
120
- constructor(dur = {}, exact = false) {
121
- if (dur instanceof Duration) {
122
- this.values = { ...dur.values };
123
- }
124
- else if (typeof dur === 'number') {
125
- this.values = { milliseconds: dur };
126
- }
127
- else if (isObject(dur)) {
128
- this.values = normalizeUnits(dur);
129
- }
130
- if (exact || (dur instanceof Duration && dur.matrix === exactMatrix)) {
131
- // Set the conversion matrix to use
132
- this.matrix = exactMatrix;
133
- }
134
- }
135
- withValues(values) {
136
- return new Duration(values, this.matrix === exactMatrix);
137
- }
138
- /** Get the years. */
139
- get years() {
140
- return this.values.years || 0;
141
- }
142
- /** Get the months. */
143
- get months() {
144
- return this.values.months || 0;
145
- }
146
- /** Get the weeks. */
147
- get weeks() {
148
- return this.values.weeks || 0;
149
- }
150
- /** Get the days. */
151
- get days() {
152
- return this.values.days || 0;
153
- }
154
- /** Get the hours. */
155
- get hours() {
156
- return this.values.hours || 0;
157
- }
158
- /** Get the minutes. */
159
- get minutes() {
160
- return this.values.minutes || 0;
161
- }
162
- /** Get the seconds. */
163
- get seconds() {
164
- return this.values.seconds || 0;
165
- }
166
- /** Get the milliseconds. */
167
- get milliseconds() {
168
- return this.values.milliseconds || 0;
169
- }
170
- /**
171
- * Get the value of unit.
172
- * @param {string} unit - a unit such as 'minute' or 'day'
173
- * @example new Duration({years: 2, days: 3}).get('years') // 2
174
- * @example new Duration({years: 2, days: 3}).get('months') // 0
175
- * @example new Duration({years: 2, days: 3}).get('days') // 3
176
- * @return {number}
177
- */
178
- get(unit) {
179
- return this.values[UNITS_PLURAL[unit.toLowerCase()]] ?? 0;
180
- }
181
- add(duration) {
182
- const dur = new Duration(duration);
183
- const result = {};
184
- for (const k of orderedUnits) {
185
- if (dur.values[k] || this.values[k]) {
186
- result[k] = dur.get(k) + this.get(k);
187
- }
188
- }
189
- return this.withValues(result);
190
- }
191
- /**
192
- * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
193
- * @param {Duration|Object|number} duration - The amount to subtract.
194
- * @return {Duration}
195
- */
196
- subtract(duration) {
197
- const dur = new Duration(duration);
198
- return this.add(dur.negated());
199
- }
200
- /**
201
- * Return the negative of this Duration.
202
- * @example
203
- ```js
204
- new Duration({ hours: 1, seconds: 30 }).negated().toObject()
205
- // { hours: -1, seconds: -30 }
206
- ```
207
- * @returns {Duration}
208
- */
209
- negated() {
210
- const negated = {};
211
- for (const k of Object.keys(this.values)) {
212
- negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
213
- }
214
- return this.withValues(negated);
215
- }
216
- /**
217
- * Return the absolute values of this Duration.
218
- * @example
219
- ```js
220
- new Duration({ hours: 1, seconds: -30 }).abs().toObject()
221
- // { hours: 1, seconds: 30 }
222
- ```
223
- * @returns {Duration}
224
- */
225
- abs() {
226
- const parts = {};
227
- for (const k of Object.keys(this.values)) {
228
- parts[k] = Math.abs(this.values[k]);
229
- }
230
- return this.withValues(parts);
231
- }
232
- shiftToAll() {
233
- return this.shiftTo('years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds');
234
- }
235
- shiftTo(...units) {
236
- if (units.length === 0) {
237
- return this;
238
- }
239
- units = units.map((u) => UNITS_PLURAL[u.toLowerCase()]);
240
- const built = {};
241
- const accumulated = {};
242
- const vals = this.toObject();
243
- let lastUnit;
244
- for (const toUnit of orderedUnits) {
245
- if (units.includes(toUnit)) {
246
- lastUnit = toUnit;
247
- let own = 0;
248
- // anything we haven't boiled down yet should get boiled to this unit
249
- for (const fromUnit in accumulated) {
250
- own += accumulated[fromUnit] * this.matrix[fromUnit][toUnit];
251
- accumulated[fromUnit] = 0;
252
- }
253
- // plus anything that's already in this unit
254
- if (typeof vals[toUnit] === 'number') {
255
- own += vals[toUnit];
256
- }
257
- const i = Math.trunc(own);
258
- built[toUnit] = i;
259
- accumulated[toUnit] = (own * 1000 - i * 1000) / 1000;
260
- // plus anything further down the chain that should be rolled up in to this
261
- for (const fromUnit in vals) {
262
- if (orderedUnits.indexOf(fromUnit) > orderedUnits.indexOf(toUnit)) {
263
- convert(this.matrix, vals, fromUnit, built, toUnit);
264
- }
265
- }
266
- }
267
- else if (isNumber(vals[toUnit])) {
268
- accumulated[toUnit] = vals[toUnit];
269
- }
270
- }
271
- // anything leftover becomes the decimal for the last unit
272
- // lastUnit must be defined since units is not empty
273
- for (const key in accumulated) {
274
- if (accumulated[key] !== 0) {
275
- built[lastUnit] +=
276
- key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
277
- }
278
- }
279
- return this.withValues(built);
280
- }
281
- total(unit) {
282
- return this.shiftTo(unit).get(unit);
283
- }
284
- exact(unit) {
285
- if (unit)
286
- return new Duration(this, true).total(unit);
287
- this.matrix = exactMatrix;
288
- return this;
289
- }
290
- toObject() {
291
- return { ...this.values };
292
- }
293
- normalize() {
294
- const values = this.toObject();
295
- normalizeValues(this.matrix, values);
296
- return this.withValues(values);
297
- }
298
- rescale() {
299
- const dur = this.normalize().shiftToAll();
300
- const vals = removeZeroes(dur.values);
301
- return this.withValues(vals);
302
- }
303
- /**
304
- * Returns an ISO 8601-compliant string representation of this Duration.
305
- * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
306
- * @example new Duration({ years: 3, seconds: 45 }).toString() // 'P3YT45S'
307
- * @example new Duration({ months: 4, seconds: 45 }).toString() // 'P4MT45S'
308
- * @example new Duration({ months: 5 }).toString() // 'P5M'
309
- * @example new Duration({ minutes: 5 }).toString() // 'PT5M'
310
- * @example new Duration({ milliseconds: 6 }).toString() // 'PT0.006S'
311
- * @return {string}
312
- */
313
- toISOString() {
314
- let s = 'P';
315
- const months = this.get('quarters') * 3 + this.months;
316
- if (this.years !== 0)
317
- s += `${this.years}Y`;
318
- if (months !== 0)
319
- s += `${months}M`;
320
- if (this.weeks !== 0)
321
- s += `${this.weeks}W`;
322
- if (this.days !== 0)
323
- s += `${this.days}D`;
324
- if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
325
- s += 'T';
326
- if (this.hours !== 0)
327
- s += `${this.hours}H`;
328
- if (this.minutes !== 0)
329
- s += `${this.minutes}M`;
330
- if (this.seconds !== 0 || this.milliseconds !== 0)
331
- // this will handle "floating point madness" by removing extra decimal places
332
- // https://stackoverflow.com/questions/588004/is-floating-point-math-broken
333
- s += `${round(this.seconds + this.milliseconds / 1000, 3)}S`;
334
- if (s === 'P')
335
- s += 'T0S';
336
- return s;
337
- }
338
- toString() {
339
- return this.toISOString();
340
- }
341
- /**
342
- * Create a Duration from an ISO 8601 duration string.
343
- *
344
- * @example
345
- ```js
346
- Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject()
347
- // { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
348
- Duration.fromISO('PT23H').toObject()
349
- // { hours: 23 }
350
- Duration.fromISO('P5Y3M').toObject()
351
- // { years: 5, months: 3 }
352
- ```
353
- * @return {Duration}
354
- */
355
- static fromISO(text) {
356
- const [parsed] = parseISODuration(text);
357
- if (parsed)
358
- return new Duration(parsed);
359
- throw new ValueError(`The input "${text}" can't be parsed as ISO 8601`);
360
- }
361
- }
362
- function normalizeUnits(obj) {
363
- const vals = {};
364
- for (const unit of Object.keys(obj)) {
365
- if (obj[unit] != null)
366
- vals[UNITS_PLURAL[unit]] = obj[unit];
367
- }
368
- return vals;
369
- }
370
- function antiTrunc(n) {
371
- return n < 0 ? Math.floor(n) : Math.ceil(n);
372
- }
373
- // NB: mutates parameters
374
- function convert(matrix, sources, fromUnit, result, toUnit) {
375
- const conv = matrix[toUnit][fromUnit];
376
- const raw = sources[fromUnit] / conv;
377
- const sameSign = Math.sign(raw) === Math.sign(result[toUnit]);
378
- // ok, so this is wild, but see the matrix in the tests
379
- const added = !sameSign && result[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);
380
- result[toUnit] += added;
381
- sources[fromUnit] -= added * conv;
382
- }
383
- // NB: mutates parameters
384
- function normalizeValues(matrix, vals) {
385
- reverseUnits.reduce((previous, current) => {
386
- if (vals[current]) {
387
- if (previous) {
388
- convert(matrix, vals, previous, vals, current);
389
- }
390
- return current;
391
- }
392
- return previous;
393
- }, null);
394
- }
395
- // Remove all properties with a value of 0 from an object
396
- function removeZeroes(vals) {
397
- return pick(vals, (value) => value !== 0);
398
- }