@noeldemartin/utils 0.7.3 → 0.8.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 (234) hide show
  1. package/dist/_virtual/_rolldown/runtime.js +13 -0
  2. package/dist/fluent/FluentArray.d.ts +48 -0
  3. package/dist/fluent/FluentArray.js +48 -0
  4. package/dist/fluent/FluentArray.js.map +1 -0
  5. package/dist/fluent/FluentObject.d.ts +16 -0
  6. package/dist/fluent/FluentObject.js +45 -0
  7. package/dist/fluent/FluentObject.js.map +1 -0
  8. package/dist/fluent/FluentString.d.ts +21 -0
  9. package/dist/fluent/FluentString.js +28 -0
  10. package/dist/fluent/FluentString.js.map +1 -0
  11. package/dist/fluent/facade.d.ts +17 -0
  12. package/dist/fluent/facade.js +45 -0
  13. package/dist/fluent/facade.js.map +1 -0
  14. package/dist/fluent/index.d.ts +29 -0
  15. package/dist/fluent/index.js +41 -0
  16. package/dist/fluent/index.js.map +1 -0
  17. package/dist/fluent/invade.d.ts +6 -0
  18. package/dist/fluent/invade.js +8 -0
  19. package/dist/fluent/invade.js.map +1 -0
  20. package/dist/fluent/lazyFacade.d.ts +16 -0
  21. package/dist/fluent/lazyFacade.js +67 -0
  22. package/dist/fluent/lazyFacade.js.map +1 -0
  23. package/dist/fluent/noop.d.ts +4 -0
  24. package/dist/fluent/noop.js +6 -0
  25. package/dist/fluent/noop.js.map +1 -0
  26. package/dist/fluent/required.d.ts +5 -0
  27. package/dist/fluent/required.js +32 -0
  28. package/dist/fluent/required.js.map +1 -0
  29. package/dist/fluent/tap.d.ts +7 -0
  30. package/dist/fluent/tap.js +22 -0
  31. package/dist/fluent/tap.js.map +1 -0
  32. package/dist/fluent/value.d.ts +5 -0
  33. package/dist/fluent/value.js +8 -0
  34. package/dist/fluent/value.js.map +1 -0
  35. package/dist/fluent/when.d.ts +6 -0
  36. package/dist/fluent/when.js +11 -0
  37. package/dist/fluent/when.js.map +1 -0
  38. package/dist/helpers/InMemoryStorageService.d.ts +8 -0
  39. package/dist/helpers/InMemoryStorageService.js +16 -0
  40. package/dist/helpers/InMemoryStorageService.js.map +1 -0
  41. package/dist/helpers/IndexedDBMap.d.ts +17 -0
  42. package/dist/helpers/IndexedDBMap.js +52 -0
  43. package/dist/helpers/IndexedDBMap.js.map +1 -0
  44. package/dist/helpers/JSError.d.ts +14 -0
  45. package/dist/helpers/JSError.js +14 -0
  46. package/dist/helpers/JSError.js.map +1 -0
  47. package/dist/helpers/ListenersManager.d.ts +15 -0
  48. package/dist/helpers/ListenersManager.js +23 -0
  49. package/dist/helpers/ListenersManager.js.map +1 -0
  50. package/dist/helpers/MagicObject.d.ts +29 -0
  51. package/dist/helpers/MagicObject.js +77 -0
  52. package/dist/helpers/MagicObject.js.map +1 -0
  53. package/dist/helpers/ObjectsMap.d.ts +28 -0
  54. package/dist/helpers/ObjectsMap.js +86 -0
  55. package/dist/helpers/ObjectsMap.js.map +1 -0
  56. package/dist/helpers/PromisedValue.d.ts +32 -0
  57. package/dist/helpers/PromisedValue.js +68 -0
  58. package/dist/helpers/PromisedValue.js.map +1 -0
  59. package/dist/helpers/Semaphore.d.ts +14 -0
  60. package/dist/helpers/Semaphore.js +45 -0
  61. package/dist/helpers/Semaphore.js.map +1 -0
  62. package/dist/helpers/Storage.d.ts +17 -0
  63. package/dist/helpers/Storage.js +39 -0
  64. package/dist/helpers/Storage.js.map +1 -0
  65. package/dist/helpers/array_helpers.d.ts +57 -0
  66. package/dist/helpers/array_helpers.js +208 -0
  67. package/dist/helpers/array_helpers.js.map +1 -0
  68. package/dist/helpers/boolean_helpers.d.ts +4 -0
  69. package/dist/helpers/boolean_helpers.js +10 -0
  70. package/dist/helpers/boolean_helpers.js.map +1 -0
  71. package/dist/helpers/caching_helpers.d.ts +17 -0
  72. package/dist/helpers/caching_helpers.js +55 -0
  73. package/dist/helpers/caching_helpers.js.map +1 -0
  74. package/dist/helpers/chaos_helpers.d.ts +6 -0
  75. package/dist/helpers/chaos_helpers.js +11 -0
  76. package/dist/helpers/chaos_helpers.js.map +1 -0
  77. package/dist/helpers/date_helpers.d.ts +4 -0
  78. package/dist/helpers/date_helpers.js +15 -0
  79. package/dist/helpers/date_helpers.js.map +1 -0
  80. package/dist/helpers/deprecated.d.ts +24 -0
  81. package/dist/helpers/env.d.ts +9 -0
  82. package/dist/helpers/env.js +42 -0
  83. package/dist/helpers/env.js.map +1 -0
  84. package/dist/helpers/error_helpers.d.ts +12 -0
  85. package/dist/helpers/error_helpers.js +20 -0
  86. package/dist/helpers/error_helpers.js.map +1 -0
  87. package/dist/helpers/escape_helpers.d.ts +5 -0
  88. package/dist/helpers/escape_helpers.js +11 -0
  89. package/dist/helpers/escape_helpers.js.map +1 -0
  90. package/dist/helpers/file_helpers.d.ts +4 -0
  91. package/dist/helpers/file_helpers.js +16 -0
  92. package/dist/helpers/file_helpers.js.map +1 -0
  93. package/dist/helpers/format_helpers.d.ts +7 -0
  94. package/dist/helpers/format_helpers.js +28 -0
  95. package/dist/helpers/format_helpers.js.map +1 -0
  96. package/dist/helpers/hash_helpers.d.ts +4 -0
  97. package/dist/helpers/hash_helpers.js +156 -0
  98. package/dist/helpers/hash_helpers.js.map +1 -0
  99. package/dist/helpers/identity_helpers.d.ts +5 -0
  100. package/dist/helpers/identity_helpers.js +15 -0
  101. package/dist/helpers/identity_helpers.js.map +1 -0
  102. package/dist/helpers/location_helpers.d.ts +8 -0
  103. package/dist/helpers/location_helpers.js +37 -0
  104. package/dist/helpers/location_helpers.js.map +1 -0
  105. package/dist/helpers/logical_helpers.d.ts +4 -0
  106. package/dist/helpers/logical_helpers.js +13 -0
  107. package/dist/helpers/logical_helpers.js.map +1 -0
  108. package/dist/helpers/math_helpers.d.ts +5 -0
  109. package/dist/helpers/math_helpers.js +12 -0
  110. package/dist/helpers/math_helpers.js.map +1 -0
  111. package/dist/helpers/mixin_helpers.d.ts +20 -0
  112. package/dist/helpers/mixin_helpers.js +43 -0
  113. package/dist/helpers/mixin_helpers.js.map +1 -0
  114. package/dist/helpers/network_helpers.d.ts +4 -0
  115. package/dist/helpers/network_helpers.js +8 -0
  116. package/dist/helpers/network_helpers.js.map +1 -0
  117. package/dist/helpers/object_helpers.d.ts +58 -0
  118. package/dist/helpers/object_helpers.js +179 -0
  119. package/dist/helpers/object_helpers.js.map +1 -0
  120. package/dist/helpers/promise_helpers.d.ts +10 -0
  121. package/dist/helpers/promise_helpers.js +25 -0
  122. package/dist/helpers/promise_helpers.js.map +1 -0
  123. package/dist/helpers/replacements-scope.js +21 -0
  124. package/dist/helpers/replacements-scope.js.map +1 -0
  125. package/dist/helpers/replacements.d.ts +5 -0
  126. package/dist/helpers/replacements.js +34 -0
  127. package/dist/helpers/replacements.js.map +1 -0
  128. package/dist/helpers/runtime_helpers.d.ts +4 -0
  129. package/dist/helpers/runtime_helpers.js +8 -0
  130. package/dist/helpers/runtime_helpers.js.map +1 -0
  131. package/dist/helpers/string_helpers.d.ts +17 -0
  132. package/dist/helpers/string_helpers.js +42 -0
  133. package/dist/helpers/string_helpers.js.map +1 -0
  134. package/dist/helpers/time_constants.d.ts +15 -0
  135. package/dist/helpers/time_constants.js +17 -0
  136. package/dist/helpers/time_constants.js.map +1 -0
  137. package/dist/helpers/time_helpers.d.ts +24 -0
  138. package/dist/helpers/time_helpers.js +57 -0
  139. package/dist/helpers/time_helpers.js.map +1 -0
  140. package/dist/helpers/url_helpers.d.ts +24 -0
  141. package/dist/helpers/url_helpers.js +90 -0
  142. package/dist/helpers/url_helpers.js.map +1 -0
  143. package/dist/helpers/value_helpers.d.ts +7 -0
  144. package/dist/helpers/value_helpers.js +11 -0
  145. package/dist/helpers/value_helpers.js.map +1 -0
  146. package/dist/index.d.ts +53 -0
  147. package/dist/index.js +49 -0
  148. package/dist/types/arrays.d.ts +12 -0
  149. package/dist/types/classes.d.ts +12 -0
  150. package/dist/types/helpers.d.ts +36 -0
  151. package/dist/types/helpers.js +6 -0
  152. package/dist/types/helpers.js.map +1 -0
  153. package/dist/types/objects.d.ts +8 -0
  154. package/package.json +38 -52
  155. package/src/fluent/FluentArray.test.ts +2 -9
  156. package/src/fluent/FluentArray.ts +6 -5
  157. package/src/fluent/FluentObject.ts +2 -4
  158. package/src/fluent/FluentString.test.ts +1 -8
  159. package/src/fluent/FluentString.ts +0 -2
  160. package/src/fluent/facade.test.ts +16 -4
  161. package/src/fluent/facade.ts +6 -4
  162. package/src/fluent/index.test.ts +3 -8
  163. package/src/fluent/index.ts +3 -3
  164. package/src/fluent/invade.test.ts +1 -5
  165. package/src/fluent/invade.ts +1 -1
  166. package/src/fluent/lazyFacade.test.ts +191 -0
  167. package/src/fluent/lazyFacade.ts +115 -0
  168. package/src/fluent/required.test.ts +1 -5
  169. package/src/fluent/required.ts +2 -4
  170. package/src/fluent/tap.test.ts +2 -9
  171. package/src/fluent/tap.ts +4 -3
  172. package/src/fluent/value.test.ts +1 -4
  173. package/src/fluent/when.test.ts +1 -6
  174. package/src/fluent/when.ts +2 -2
  175. package/src/helpers/InMemoryStorageService.ts +13 -0
  176. package/src/helpers/IndexedDBMap.ts +0 -2
  177. package/src/helpers/JSError.test.ts +1 -6
  178. package/src/helpers/JSError.ts +0 -2
  179. package/src/helpers/ListenersManager.test.ts +3 -7
  180. package/src/helpers/ListenersManager.ts +2 -4
  181. package/src/helpers/MagicObject.test.ts +14 -8
  182. package/src/helpers/MagicObject.ts +12 -3
  183. package/src/helpers/ObjectsMap.test.ts +1 -3
  184. package/src/helpers/ObjectsMap.ts +1 -5
  185. package/src/helpers/PromisedValue.test.ts +1 -3
  186. package/src/helpers/PromisedValue.ts +5 -6
  187. package/src/helpers/Semaphore.test.ts +6 -10
  188. package/src/helpers/Semaphore.ts +0 -2
  189. package/src/helpers/Storage.test.ts +47 -0
  190. package/src/helpers/Storage.ts +11 -19
  191. package/src/helpers/array_helpers.test.ts +127 -38
  192. package/src/helpers/array_helpers.ts +137 -78
  193. package/src/helpers/caching_helpers.test.ts +1 -3
  194. package/src/helpers/caching_helpers.ts +2 -2
  195. package/src/helpers/date_helpers.test.ts +1 -4
  196. package/src/helpers/date_helpers.ts +1 -1
  197. package/src/helpers/env.ts +5 -1
  198. package/src/helpers/error_helpers.test.ts +9 -8
  199. package/src/helpers/error_helpers.ts +11 -11
  200. package/src/helpers/format_helpers.test.ts +2 -4
  201. package/src/helpers/hash_helpers.test.ts +1 -4
  202. package/src/helpers/hash_helpers.ts +3 -3
  203. package/src/helpers/identity_helpers.test.ts +1 -3
  204. package/src/helpers/index.ts +3 -0
  205. package/src/helpers/logical_helpers.test.ts +1 -3
  206. package/src/helpers/logical_helpers.ts +1 -1
  207. package/src/helpers/math_helpers.test.ts +1 -3
  208. package/src/helpers/mixin_helpers.stubs.ts +1 -13
  209. package/src/helpers/mixin_helpers.test.ts +2 -7
  210. package/src/helpers/mixin_helpers.ts +6 -9
  211. package/src/helpers/object_helpers.test.ts +32 -19
  212. package/src/helpers/object_helpers.ts +43 -21
  213. package/src/helpers/promise_helpers.test.ts +1 -4
  214. package/src/helpers/promise_helpers.ts +9 -9
  215. package/src/helpers/replacements-scope.ts +15 -0
  216. package/src/helpers/replacements.test.ts +23 -0
  217. package/src/helpers/replacements.ts +52 -0
  218. package/src/helpers/runtime_helpers.ts +3 -3
  219. package/src/helpers/string_helpers.test.ts +3 -5
  220. package/src/helpers/time_constants.ts +13 -0
  221. package/src/helpers/time_helpers.ts +35 -0
  222. package/src/helpers/url_helpers.test.ts +12 -4
  223. package/src/helpers/url_helpers.ts +9 -15
  224. package/src/helpers/value_helpers.test.ts +12 -0
  225. package/src/helpers/value_helpers.ts +6 -0
  226. package/src/types/arrays.test.ts +1 -4
  227. package/src/types/classes.ts +1 -0
  228. package/src/types/helpers.test.ts +1 -6
  229. package/src/types/helpers.ts +6 -5
  230. package/src/types/objects.test.ts +1 -4
  231. package/src/types/objects.ts +3 -3
  232. package/dist/noeldemartin-utils.d.ts +0 -901
  233. package/dist/noeldemartin-utils.js +0 -1473
  234. package/dist/noeldemartin-utils.js.map +0 -1
@@ -1,10 +1,10 @@
1
- import { describe, expect, it } from 'vitest';
2
1
  import { tt } from '@noeldemartin/testing';
3
2
  import type { Expect } from '@noeldemartin/testing';
4
-
5
3
  import { toString } from '@noeldemartin/utils/helpers/object_helpers';
6
- import type { Equals } from '@noeldemartin/utils/types';
4
+ import type { DeepKeyOf, Equals } from '@noeldemartin/utils/types';
5
+ import { describe, expect, it } from 'vite-plus/test';
7
6
 
7
+ import type { ArraySortDirection, ArraySortFieldDirection } from './array_helpers';
8
8
  import {
9
9
  arrayDiff,
10
10
  arrayEquals,
@@ -22,10 +22,10 @@ import {
22
22
  arrayWithout,
23
23
  arrayWithoutIndexes,
24
24
  arrayZip,
25
+ reduceBy,
25
26
  } from './array_helpers';
26
27
 
27
28
  describe('Array helpers', () => {
28
-
29
29
  it('compares arrays', () => {
30
30
  expect(arrayEquals(['one'], ['one'])).toBe(true);
31
31
  expect(arrayEquals(['one'], ['one', 'two'])).toBe(false);
@@ -92,14 +92,26 @@ describe('Array helpers', () => {
92
92
  expect(arraySorted([1, 3, 2])).toEqual([1, 2, 3]);
93
93
  expect(arraySorted([1, 3, 2], 'asc')).toEqual([1, 2, 3]);
94
94
  expect(arraySorted([1, 3, 2], 'desc')).toEqual([3, 2, 1]);
95
+ expect(arraySorted([10, 2, 1])).toEqual([1, 2, 10]);
96
+ expect(arraySorted([10, 2, 1], 'asc')).toEqual([1, 2, 10]);
95
97
  });
96
98
 
97
99
  it('sorts items by field', () => {
98
- const items = [{ name: 'Son Goku' }, { name: 'Astroboy' }, { name: 'Zetman' }];
100
+ const items = [
101
+ { name: 'Son Goku' },
102
+ { name: 'Astroboy' },
103
+ { name: 'Guts' },
104
+ { name: 'Griffith' },
105
+ { name: 'Zetman' },
106
+ ];
107
+
108
+ const expectSorted = (field: DeepKeyOf<(typeof items)[number]>, direction?: ArraySortDirection) => {
109
+ return expect(arraySorted(items, field, direction).map(({ name }) => name));
110
+ };
99
111
 
100
- expect(arraySorted(items, 'name').map((item) => item.name)).toEqual(['Astroboy', 'Son Goku', 'Zetman']);
101
- expect(arraySorted(items, 'name', 'asc').map((item) => item.name)).toEqual(['Astroboy', 'Son Goku', 'Zetman']);
102
- expect(arraySorted(items, 'name', 'desc').map((item) => item.name)).toEqual(['Zetman', 'Son Goku', 'Astroboy']);
112
+ expectSorted('name').toEqual(['Astroboy', 'Griffith', 'Guts', 'Son Goku', 'Zetman']);
113
+ expectSorted('name', 'asc').toEqual(['Astroboy', 'Griffith', 'Guts', 'Son Goku', 'Zetman']);
114
+ expectSorted('name', 'desc').toEqual(['Zetman', 'Son Goku', 'Guts', 'Griffith', 'Astroboy']);
103
115
  });
104
116
 
105
117
  it('sorts items by nested field', () => {
@@ -109,16 +121,12 @@ describe('Array helpers', () => {
109
121
  { author: { name: 'J.R.R. Tolkien' } },
110
122
  ];
111
123
 
112
- expect(arraySorted(items, 'author.name').map((item) => item.author.name)).toEqual([
113
- 'Arthur Conan Doyle',
114
- 'Brandom Sanderson',
115
- 'J.R.R. Tolkien',
116
- ]);
117
- expect(arraySorted(items, 'author.name', 'desc').map((item) => item.author.name)).toEqual([
118
- 'J.R.R. Tolkien',
119
- 'Brandom Sanderson',
120
- 'Arthur Conan Doyle',
121
- ]);
124
+ const expectSorted = (field: DeepKeyOf<(typeof items)[number]>, direction?: ArraySortDirection) => {
125
+ return expect(arraySorted(items, field, direction).map(({ author }) => author.name));
126
+ };
127
+
128
+ expectSorted('author.name').toEqual(['Arthur Conan Doyle', 'Brandom Sanderson', 'J.R.R. Tolkien']);
129
+ expectSorted('author.name', 'desc').toEqual(['J.R.R. Tolkien', 'Brandom Sanderson', 'Arthur Conan Doyle']);
122
130
  });
123
131
 
124
132
  it('sorts items by field with undefined value', () => {
@@ -129,18 +137,69 @@ describe('Array helpers', () => {
129
137
  expect(arraySorted(items, 'completed', 'desc').map((item) => item.completed)).toEqual([true, true, undefined]);
130
138
  });
131
139
 
140
+ it('sorts items by date field', () => {
141
+ const items = [
142
+ { name: 'Second', createdAt: new Date('2024-02-01') },
143
+ { name: 'Unknown', createdAt: undefined },
144
+ { name: 'Third', createdAt: new Date('2024-03-01') },
145
+ { name: 'First', createdAt: new Date('2024-01-01') },
146
+ ];
147
+
148
+ expect(arraySorted(items, 'createdAt').map(({ name }) => name)).toEqual([
149
+ 'Unknown',
150
+ 'First',
151
+ 'Second',
152
+ 'Third',
153
+ ]);
154
+ expect(arraySorted(items, 'createdAt', 'desc').map(({ name }) => name)).toEqual([
155
+ 'Third',
156
+ 'Second',
157
+ 'First',
158
+ 'Unknown',
159
+ ]);
160
+ });
161
+
132
162
  it('sorts items by multiple fields', () => {
133
- const sonGokuKid = { name: 'Son Goku', age: 11 };
134
- const sonGokuAdult = { name: 'Son Goku', age: 31 };
135
- const astroboy = { name: 'Astroboy', age: 18 };
136
- const zetman = { name: 'Zetman', age: 16 };
137
- const items = [sonGokuAdult, sonGokuKid, astroboy, zetman];
138
-
139
- expect(arraySorted(items, ['name'])).toEqual([astroboy, sonGokuAdult, sonGokuKid, zetman]);
140
- expect(arraySorted(items, ['name'], 'desc')).toEqual([zetman, sonGokuAdult, sonGokuKid, astroboy]);
141
- expect(arraySorted(items, ['name', 'age'])).toEqual([astroboy, sonGokuKid, sonGokuAdult, zetman]);
142
- expect(arraySorted(items, ['name', 'age'], 'desc')).toEqual([zetman, sonGokuAdult, sonGokuKid, astroboy]);
143
- expect(arraySorted(items, ['age'])).toEqual([sonGokuKid, zetman, astroboy, sonGokuAdult]);
163
+ const items = [
164
+ { name: 'Son Goku', age: 31 },
165
+ { name: 'Son Goku', age: 11 },
166
+ { name: 'Astroboy', age: 18 },
167
+ { name: 'Zetman', age: 16 },
168
+ ];
169
+
170
+ const expectSorted = (fields: DeepKeyOf<(typeof items)[number]>[], direction?: ArraySortDirection) => {
171
+ return expect(arraySorted(items, fields, direction).map(({ name, age }) => `${name}:${age}`));
172
+ };
173
+
174
+ expectSorted(['name']).toEqual(['Astroboy:18', 'Son Goku:31', 'Son Goku:11', 'Zetman:16']);
175
+ expectSorted(['name'], 'desc').toEqual(['Zetman:16', 'Son Goku:31', 'Son Goku:11', 'Astroboy:18']);
176
+ expectSorted(['name', 'age']).toEqual(['Astroboy:18', 'Son Goku:11', 'Son Goku:31', 'Zetman:16']);
177
+ expectSorted(['name', 'age'], 'desc').toEqual(['Zetman:16', 'Son Goku:31', 'Son Goku:11', 'Astroboy:18']);
178
+ expectSorted(['age']).toEqual(['Son Goku:11', 'Zetman:16', 'Astroboy:18', 'Son Goku:31']);
179
+ });
180
+
181
+ it('sorts items by multiple fields and directions', () => {
182
+ const items = [
183
+ { title: 'Happy', score: 7 },
184
+ { title: 'Monster', score: 10 },
185
+ { title: 'Pluto', score: 9 },
186
+ { title: 'Billy Bat', score: 9 },
187
+ { title: 'Billy Bat', score: 8 },
188
+ ];
189
+
190
+ const expectSorted = (fields: ArraySortFieldDirection<(typeof items)[number]>[]) => {
191
+ return expect(arraySorted(items, fields).map(({ title, score }) => `${title}:${score}`));
192
+ };
193
+
194
+ expectSorted([
195
+ ['title', 'asc'],
196
+ ['score', 'desc'],
197
+ ]).toEqual(['Billy Bat:9', 'Billy Bat:8', 'Happy:7', 'Monster:10', 'Pluto:9']);
198
+
199
+ expectSorted([
200
+ ['score', 'desc'],
201
+ ['title', 'asc'],
202
+ ]).toEqual(['Monster:10', 'Billy Bat:9', 'Pluto:9', 'Billy Bat:8', 'Happy:7']);
144
203
  });
145
204
 
146
205
  it('groups items', () => {
@@ -200,13 +259,11 @@ describe('Array helpers', () => {
200
259
  it('projects properties', () => {
201
260
  // Arrange.
202
261
  class User {
203
-
204
262
  constructor(public role: string) {}
205
263
 
206
264
  public isAdmin(): boolean {
207
265
  return this.role === 'admin';
208
266
  }
209
-
210
267
  }
211
268
 
212
269
  const admin = new User('admin');
@@ -219,13 +276,11 @@ describe('Array helpers', () => {
219
276
  it('filters by methods and values', () => {
220
277
  // Arrange.
221
278
  class User {
222
-
223
279
  constructor(public role: string) {}
224
280
 
225
281
  public isAdmin(): boolean {
226
282
  return this.role === 'admin';
227
283
  }
228
-
229
284
  }
230
285
 
231
286
  const admin = new User('admin');
@@ -253,14 +308,43 @@ describe('Array helpers', () => {
253
308
  expect(arrayFrom(['foo', 'bar'])).toEqual(['foo', 'bar']);
254
309
  expect(arrayFrom(new Set(['foo', 'bar']))).toEqual(['foo', 'bar']);
255
310
  expect(arrayFrom(null)).toEqual([null]);
256
- expect(arrayFrom(null, true)).toEqual([]);
311
+ expect(arrayFrom(null, { ignoreEmptyValues: true })).toEqual([]);
312
+ });
313
+
314
+ it('reduces by key', () => {
315
+ const items = [
316
+ { id: '1', name: 'Alice' },
317
+ { id: '2', name: 'Bob' },
318
+ ];
319
+
320
+ const result = reduceBy(items, 'id');
321
+
322
+ expect(result).toEqual({
323
+ 1: { id: '1', name: 'Alice' },
324
+ 2: { id: '2', name: 'Bob' },
325
+ });
257
326
  });
258
327
 
328
+ it('reduces by key with projection', () => {
329
+ const items = [
330
+ { id: '1', name: 'Alice' },
331
+ { id: '2', name: 'Bob' },
332
+ ];
333
+
334
+ const result = reduceBy(items, 'id', (item) => item.name);
335
+
336
+ expect(result).toEqual({
337
+ 1: 'Alice',
338
+ 2: 'Bob',
339
+ });
340
+ });
259
341
  });
260
342
 
343
+ // oxlint-disable-next-line no-unassigned-vars
261
344
  let enabled: boolean | undefined;
262
- const filteredItems = arrayFilter(['foo', null, 'bar', undefined]);
263
- const filteredConditionalItems = arrayFilter(['foo', null, enabled && 'bar', undefined]);
345
+ const sorting: { field: 'id'; direction: ArraySortDirection }[] = [];
346
+ const filteredItems = arrayFilter(['foo' as string, null, 'bar', undefined]);
347
+ const filteredConditionalItems = arrayFilter(['foo' as string, null, enabled && 'bar', undefined]);
264
348
  const filteredConstItems = arrayFilter(['foo' as const, null, enabled && 'bar', undefined]);
265
349
  const arrayFromNumber = arrayFrom(42);
266
350
  const arrayFromSet = arrayFrom(new Set(['foo']));
@@ -268,9 +352,13 @@ const arrayFromArray = arrayFrom([new Date()]);
268
352
  const arrayFromConditional = arrayFrom(Date.now() ? 42 : [42]);
269
353
  const groupedByKey = arrayGroupBy([{ id: 'Foo Bar' }], 'id');
270
354
  const groupedByFunction = arrayGroupBy([{ id: 'Foo Bar' }], (item) => (item.id ? 'one' : 'two'));
355
+ const sortedItems = arraySorted([{ id: 'Foo Bar' }], [['id', 'asc']]);
356
+ const sortedItemsReadonly = arraySorted(
357
+ [{ id: 'Foo Bar' }],
358
+ sorting.map(({ field, direction }) => [field, direction] as const),
359
+ );
271
360
 
272
361
  describe('Array helpers types', () => {
273
-
274
362
  it(
275
363
  'has correct types',
276
364
  tt<
@@ -283,8 +371,9 @@ describe('Array helpers types', () => {
283
371
  | Expect<Equals<typeof arrayFromConditional, number[]>>
284
372
  | Expect<Equals<keyof typeof groupedByKey, string>>
285
373
  | Expect<Equals<keyof typeof groupedByFunction, 'one' | 'two'>>
374
+ | Expect<Equals<typeof sortedItems, { id: string }[]>>
375
+ | Expect<Equals<typeof sortedItemsReadonly, { id: string }[]>>
286
376
  | true
287
377
  >(),
288
378
  );
289
-
290
379
  });
@@ -1,10 +1,13 @@
1
- import type { Closure, Falsy } from '@noeldemartin/utils/types/helpers';
1
+ import type { Falsy } from '@noeldemartin/utils/types/helpers';
2
2
  import type { DeepKeyOf } from '@noeldemartin/utils/types/objects';
3
3
 
4
4
  import { compare } from './logical_helpers';
5
5
  import { deepGet, isIterable, isString, toString } from './object_helpers';
6
6
 
7
7
  export type ArrayFrom<T> = T extends Iterable<infer TItem> ? TItem[] : T[];
8
+ export type ArraySortDirection = 'asc' | 'desc';
9
+ export type ArraySortFieldDirection<T> = readonly [DeepKeyOf<T>, ArraySortDirection];
10
+ export type ArraySortCompare<T> = (a: T, b: T) => number;
8
11
 
9
12
  export function arrayClear(items: unknown[]): void {
10
13
  items.splice(0, items.length);
@@ -74,7 +77,7 @@ export function arrayWithItemAt<T>(items: T[], item: T, index: number): T[] {
74
77
 
75
78
  export function arrayGroupBy<TItem, TKey extends string>(
76
79
  items: TItem[],
77
- groupBy: (item: TItem) => TKey
80
+ groupBy: (item: TItem) => TKey,
78
81
  ): Partial<Record<TKey, TItem[]>>;
79
82
  export function arrayGroupBy<TItem, TKey extends keyof TItem>(items: TItem[], groupBy: TKey): Record<string, TItem[]>;
80
83
  export function arrayGroupBy<TItem>(
@@ -152,83 +155,102 @@ export function arrayReplace<T>(items: T[], original: T, replacement: T): boolea
152
155
  return true;
153
156
  }
154
157
 
158
+ export function arrayReversed<T>(items: T[]): T[] {
159
+ const reversed = items.slice(0);
160
+
161
+ reversed.reverse();
162
+
163
+ return reversed;
164
+ }
165
+
166
+ export function arrayShuffled<T>(items: T[]): T[] {
167
+ const shuffled = items.slice(0);
168
+
169
+ shuffle(shuffled);
170
+
171
+ return shuffled;
172
+ }
173
+
155
174
  export function arraySorted<T>(items: T[]): T[];
156
- export function arraySorted<T>(items: T[], direction: 'asc' | 'desc'): T[];
157
- export function arraySorted<T>(items: T[], compareValues: (a: T, b: T) => number): T[];
158
- export function arraySorted<T>(items: T[], field: DeepKeyOf<T>, direction?: 'asc' | 'desc'): T[];
159
- export function arraySorted<T>(items: T[], fields: DeepKeyOf<T>[], direction?: 'asc' | 'desc'): T[];
175
+ export function arraySorted<T>(items: T[], direction: ArraySortDirection): T[];
176
+ export function arraySorted<T>(items: T[], compareValues: ArraySortCompare<T>): T[];
177
+ export function arraySorted<T>(items: T[], field: DeepKeyOf<T>, direction?: ArraySortDirection): T[];
178
+ export function arraySorted<T>(items: T[], fields: DeepKeyOf<T>[], direction?: ArraySortDirection): T[];
179
+ export function arraySorted<T>(items: T[], fields: ArraySortFieldDirection<T>[]): T[];
160
180
  export function arraySorted<T>(
161
181
  items: T[],
162
- compareOrFieldOrDirection?: DeepKeyOf<T> | DeepKeyOf<T>[] | ((a: T, b: T) => number) | 'asc' | 'desc',
163
- direction?: 'asc' | 'desc',
182
+ compareOrFieldOrDirection?:
183
+ | ArraySortDirection
184
+ | ArraySortCompare<T>
185
+ | DeepKeyOf<T>
186
+ | DeepKeyOf<T>[]
187
+ | ArraySortFieldDirection<T>[],
188
+ direction?: ArraySortDirection,
164
189
  ): T[] {
165
- direction =
166
- compareOrFieldOrDirection === 'asc' || compareOrFieldOrDirection === 'desc'
167
- ? (compareOrFieldOrDirection as 'asc' | 'desc')
168
- : direction;
169
-
170
- const fieldDefaults: Partial<Record<DeepKeyOf<T>, unknown>> = {};
171
- const getDefaultValue = (sample: unknown): unknown => {
172
- switch (typeof sample) {
173
- case 'string':
174
- return '';
175
- case 'number':
176
- return Number.MIN_SAFE_INTEGER;
177
- case 'boolean':
178
- return false;
179
- default:
180
- return null;
181
- }
182
- };
183
- const getFieldValue = (object: T, field: DeepKeyOf<T>): unknown => {
184
- if (!(field in fieldDefaults)) {
185
- const sampleValue = deepGet(
186
- items.find(
187
- (item) =>
188
- deepGet(item as object, field as never) !== undefined &&
189
- deepGet(item as object, field as never) !== null,
190
- ) as object,
191
- field as never,
192
- );
193
-
194
- fieldDefaults[field] = getDefaultValue(sampleValue);
195
- }
190
+ switch (compareOrFieldOrDirection) {
191
+ case undefined:
192
+ case 'asc':
193
+ return items.slice(0).sort(compare);
194
+ case 'desc':
195
+ return items.slice(0).sort((a, b) => compare(b, a));
196
+ }
196
197
 
197
- return deepGet(object as object, field as never) ?? fieldDefaults[field];
198
- };
199
- const getComparisonFunction = (): Closure<[T, T], number> | undefined => {
200
- const compareItems =
201
- direction === 'desc'
202
- ? (field: DeepKeyOf<T>) => (a: T, b: T) => compare(getFieldValue(b, field), getFieldValue(a, field))
203
- : (field: DeepKeyOf<T>) => (a: T, b: T) => compare(getFieldValue(a, field), getFieldValue(b, field));
198
+ if (typeof compareOrFieldOrDirection === 'function') {
199
+ return items.slice(0).sort(compareOrFieldOrDirection);
200
+ }
204
201
 
205
- switch (typeof compareOrFieldOrDirection) {
206
- case 'function':
207
- return compareOrFieldOrDirection;
208
- case 'string':
209
- if (compareOrFieldOrDirection === 'asc') return;
202
+ const fields =
203
+ typeof compareOrFieldOrDirection === 'string'
204
+ ? [[compareOrFieldOrDirection, direction ?? 'asc'] as const]
205
+ : compareOrFieldOrDirection.map((field) =>
206
+ typeof field === 'string' ? ([field, direction ?? 'asc'] as const) : field,
207
+ );
210
208
 
211
- if (compareOrFieldOrDirection === 'desc') return (a, b) => compare(b, a);
209
+ return arraySortedByFields(items, fields);
210
+ }
212
211
 
213
- return compareItems(compareOrFieldOrDirection);
214
- case 'object': {
215
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
216
- const comparisonFunctions = compareOrFieldOrDirection.map((field: any) => compareItems(field));
212
+ function getSortDefaultValue(values: unknown[]): unknown {
213
+ const sample = values.find((value) => value !== undefined && value !== null);
214
+
215
+ switch (typeof sample) {
216
+ case 'string':
217
+ return '';
218
+ case 'number':
219
+ return Number.MIN_SAFE_INTEGER;
220
+ case 'boolean':
221
+ return false;
222
+ default:
223
+ if (sample instanceof Date) {
224
+ return Number.MIN_SAFE_INTEGER;
225
+ }
217
226
 
218
- return (a: T, b: T) => {
219
- for (const comparisonFunction of comparisonFunctions) {
220
- const result = comparisonFunction(a, b);
227
+ return null;
228
+ }
229
+ }
221
230
 
222
- if (result !== 0) return result;
223
- }
231
+ function arraySortedByFields<T>(items: T[], fields: readonly ArraySortFieldDirection<T>[]): T[] {
232
+ const sortKeys = fields.map(([field, fieldDirection]) => {
233
+ const values = items.map((item) => deepGet(item as object, field as never) as unknown);
234
+ const defaultValue = getSortDefaultValue(values);
224
235
 
225
- return 0;
226
- };
227
- }
236
+ return {
237
+ values: values.map((value) => (value instanceof Date ? value.getTime() : (value ?? defaultValue))),
238
+ directionSign: fieldDirection === 'desc' ? -1 : 1,
239
+ };
240
+ });
241
+ const indexes = items.map((_, index) => index);
242
+
243
+ indexes.sort((a, b) => {
244
+ for (const { values, directionSign } of sortKeys) {
245
+ const result = compare(values[a], values[b]);
246
+
247
+ if (result !== 0) return result * directionSign;
228
248
  }
229
- };
230
249
 
231
- return items.slice(0).sort(getComparisonFunction());
250
+ return 0;
251
+ });
252
+
253
+ return indexes.map((index) => items[index] as T);
232
254
  }
233
255
 
234
256
  export function arraySwap(items: unknown[], firstIndex: number, secondIndex: number): void {
@@ -238,17 +260,17 @@ export function arraySwap(items: unknown[], firstIndex: number, secondIndex: num
238
260
  export function arrayUnique<T>(items: T[], extractKey?: (item: T) => string): T[] {
239
261
  return extractKey
240
262
  ? Object.values(
241
- items.reduce(
242
- (unique, item) => {
243
- const key = extractKey(item);
263
+ items.reduce(
264
+ (unique, item) => {
265
+ const key = extractKey(item);
244
266
 
245
- unique[key] = unique[key] ?? item;
267
+ unique[key] = unique[key] ?? item;
246
268
 
247
- return unique;
248
- },
269
+ return unique;
270
+ },
249
271
  {} as Record<string, T>,
250
- ),
251
- )
272
+ ),
273
+ )
252
274
  : [...new Set(items)];
253
275
  }
254
276
 
@@ -296,17 +318,54 @@ export function arrayZip<T>(...arrays: T[][]): T[][] {
296
318
  return zippedArrays;
297
319
  }
298
320
 
299
- export function arrayFrom<T>(value: T, ignoreEmptyValues: boolean = false): ArrayFrom<T> {
321
+ export function arrayFrom<TValue, TOptions extends { ignoreEmptyValues?: boolean }>(
322
+ value: TValue,
323
+ options?: TOptions,
324
+ ): TOptions extends { ignoreEmptyValues: true } ? ArrayFrom<NonNullable<TValue>> : ArrayFrom<TValue> {
325
+ const ignoreEmptyValues = options?.ignoreEmptyValues ?? false;
300
326
  const items =
301
327
  Array.isArray(value) || (isIterable(value) && !isString(value))
302
328
  ? Array.from(value)
303
329
  : ignoreEmptyValues && (value === null || value === undefined)
304
- ? []
305
- : [value];
330
+ ? []
331
+ : [value];
306
332
 
307
- return items as ArrayFrom<T>;
333
+ return items as TOptions extends { ignoreEmptyValues: true } ? ArrayFrom<NonNullable<TValue>> : ArrayFrom<TValue>;
334
+ }
335
+
336
+ export function hasItems<T>(array: T[]): array is [T, ...T[]] {
337
+ return array.length > 0;
308
338
  }
309
339
 
310
340
  export function range(length: number): number[] {
311
341
  return Array.from({ length }, (_, item) => item);
312
342
  }
343
+
344
+ export function reduceBy<TItem, TKey extends keyof TItem, TProjection>(
345
+ items: TItem[],
346
+ key: TKey,
347
+ project: (item: TItem) => TProjection,
348
+ ): Record<string, TProjection>;
349
+ export function reduceBy<TItem, TKey extends keyof TItem>(items: TItem[], key: TKey): Record<string, TItem>;
350
+ export function reduceBy<TItem, TKey extends keyof TItem, TProjection>(
351
+ items: TItem[],
352
+ key: TKey,
353
+ project?: (item: TItem) => TProjection,
354
+ ): Record<string, TProjection> {
355
+ return items.reduce(
356
+ (acc, item) => {
357
+ acc[toString(item[key])] = project ? project(item) : (item as unknown as TProjection);
358
+
359
+ return acc;
360
+ },
361
+ {} as Record<string, TProjection>,
362
+ );
363
+ }
364
+
365
+ export function shuffle(items: unknown[]): void {
366
+ for (let i = items.length - 1; i > 0; i--) {
367
+ const j = Math.floor(Math.random() * (i + 1));
368
+
369
+ [items[i], items[j]] = [items[j], items[i]];
370
+ }
371
+ }
@@ -1,9 +1,8 @@
1
- import { describe, expect, it } from 'vitest';
1
+ import { describe, expect, it } from 'vite-plus/test';
2
2
 
3
3
  import { asyncMemo, memo, once, setAsyncMemo } from './caching_helpers';
4
4
 
5
5
  describe('Cache helpers', () => {
6
-
7
6
  it('caches results', () => {
8
7
  // Arrange
9
8
  let calls = 0;
@@ -80,5 +79,4 @@ describe('Cache helpers', () => {
80
79
  // Assert.
81
80
  expect(count).toEqual(1);
82
81
  });
83
-
84
82
  });
@@ -1,6 +1,6 @@
1
- import PromisedValue from '@noeldemartin/utils/helpers/PromisedValue';
2
1
  import { arrayFrom } from '@noeldemartin/utils/helpers/array_helpers';
3
2
  import { fail } from '@noeldemartin/utils/helpers/error_helpers';
3
+ import PromisedValue from '@noeldemartin/utils/helpers/PromisedValue';
4
4
  import type { Closure, ClosureArgs } from '@noeldemartin/utils/types';
5
5
 
6
6
  const cache: Record<string, unknown> = {};
@@ -22,7 +22,7 @@ export function memo<T>(key: string, operation: () => T): T {
22
22
  export function once<P extends ClosureArgs, R>(operation: Closure<P, R>): Closure<P, R> {
23
23
  const memory: { result?: R } = {};
24
24
 
25
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
+ // oxlint-disable-next-line typescript/no-explicit-any
26
26
  return (...params) => ('result' in memory ? memory.result : ((memory.result = operation(...params)) as any));
27
27
  }
28
28
 
@@ -1,9 +1,7 @@
1
- import { describe, expect, it } from 'vitest';
2
-
3
1
  import { parseDate } from '@noeldemartin/utils/helpers/date_helpers';
2
+ import { describe, expect, it } from 'vite-plus/test';
4
3
 
5
4
  describe('Date helpers', () => {
6
-
7
5
  it('parses dates', () => {
8
6
  expect(parseDate()).toEqual(null);
9
7
  expect(parseDate('invalid value')).toEqual(null);
@@ -12,5 +10,4 @@ describe('Date helpers', () => {
12
10
  expect(parseDate('2021-09-03T16:09:12.000Z')).toEqual(new Date(1630685352000));
13
11
  expect(parseDate(new Date(1630685352000))).toEqual(new Date(1630685352000));
14
12
  });
15
-
16
13
  });
@@ -6,7 +6,7 @@ export function parseDate(value?: unknown): Date | null {
6
6
  const time = date.getTime();
7
7
 
8
8
  return isNaN(time) || time === 0 ? null : date;
9
- } catch (error) {
9
+ } catch {
10
10
  return null;
11
11
  }
12
12
  }
@@ -15,6 +15,10 @@ function getTestingType(): 'unit' | 'e2e' | null {
15
15
  return 'unit';
16
16
  }
17
17
 
18
+ if ('__AEROGEL_E2E__' in globalThis) {
19
+ return 'e2e';
20
+ }
21
+
18
22
  return null;
19
23
  }
20
24
 
@@ -37,7 +41,7 @@ export function getEnv(): string | null {
37
41
 
38
42
  try {
39
43
  return __AEROGEL_ENV__ ?? null;
40
- } catch (error) {
44
+ } catch {
41
45
  return null;
42
46
  }
43
47
  }
@@ -1,11 +1,9 @@
1
- import { describe, expect, it } from 'vitest';
2
-
3
1
  import JSError from '@noeldemartin/utils/helpers/JSError';
2
+ import { describe, expect, it } from 'vite-plus/test';
4
3
 
5
4
  import { catchError, fail } from './error_helpers';
6
5
 
7
6
  describe('Error helpers', () => {
8
-
9
7
  it('throws an error', () => {
10
8
  const error = catchError(() => fail());
11
9
 
@@ -27,17 +25,20 @@ describe('Error helpers', () => {
27
25
 
28
26
  expect(error).not.toBeNull();
29
27
  expect(error).toBeInstanceOf(StubError);
30
- expect((error as Error).message).toBe('');
28
+ expect((error as Error).message).toBe('Custom message: 500');
31
29
  });
32
30
 
33
31
  it('throws an error class with parameters', () => {
34
- const error = catchError(() => fail(StubError, 'foobar'));
32
+ const error = catchError(() => fail(StubError, 404));
35
33
 
36
34
  expect(error).not.toBeNull();
37
35
  expect(error).toBeInstanceOf(StubError);
38
- expect((error as StubError).message).toBe('foobar');
36
+ expect((error as StubError).message).toBe('Custom message: 404');
39
37
  });
40
-
41
38
  });
42
39
 
43
- class StubError extends JSError {}
40
+ class StubError extends JSError {
41
+ constructor(errorCode: number = 500) {
42
+ super(`Custom message: ${errorCode}`);
43
+ }
44
+ }