@bemoje/map 0.2.1 → 1.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.
package/index.d.ts ADDED
@@ -0,0 +1,348 @@
1
+ import { inspect, InspectOptions } from 'util';
2
+
3
+ /**
4
+ * Interface for a View that wraps a target object.
5
+ * View methods are redirected to the wrapped object which acts as
6
+ * a surrogate 'this'.
7
+ *
8
+ * To create a method that redirects to 'target', @see {@link defineProxifiedPrototypeProperty}
9
+ */
10
+ interface IView<T extends object> {
11
+ readonly target: T;
12
+ }
13
+
14
+ declare const TARGET_SYMBOL: unique symbol;
15
+ /**
16
+ * Base class providing view functionality over a target object using the Composition pattern.
17
+ */
18
+ declare class View<Target extends object> implements IView<Target> {
19
+ private [TARGET_SYMBOL];
20
+ constructor(target: Target);
21
+ get [Symbol.toStringTag](): string;
22
+ get target(): Target;
23
+ }
24
+
25
+ type Any = any;
26
+
27
+ declare module './ExtMap' {
28
+ interface ExtMap<K, V> extends Map<K, V> {
29
+ load(entries: Iterable<[K, V]>): this;
30
+ sort(compare: (a: [K, V], b: [K, V]) => number): this;
31
+ sortByKeys(compare: (a: K, b: K) => number): this;
32
+ sortByValues(compare: (a: V, b: V) => number): this;
33
+ reverse(): this;
34
+ update(key: K, update: (value: V | undefined, key: K, map: this) => V): this;
35
+ getOrDefault(key: K, factory: (key: K, map: this) => V): V;
36
+ keysArray(): K[];
37
+ valuesArray(): V[];
38
+ entriesArray(): [K, V][];
39
+ toMap(): Map<K, V>;
40
+ toObject<K extends string, V>(): Record<K, V>;
41
+ reduce<R>(reducer: (accumulator: R, value: V, key: K) => R, initialValue: R): R;
42
+ map<NewK, NewV>(mapper: (value: V, key: K) => [NewK, NewV]): ExtMap<NewK, NewV>;
43
+ mapKeys<NewK>(mapper: (key: K, value: V) => NewK): ExtMap<NewK, V>;
44
+ mapValues<NewV>(mapper: (value: V, key: K) => NewV): ExtMap<K, NewV>;
45
+ filter(predicate: (value: V, key: K) => boolean): ExtMap<K, V>;
46
+ }
47
+ }
48
+ /**
49
+ * Minimal Extended Map class focused only on Map-specific utilities.
50
+ *
51
+ * @template K - The type of keys in the map
52
+ * @template V - The type of values in the map
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * import { map as iterMap, filter } from 'iter-tools'
57
+ *
58
+ * const extMap = new ExtMap<string, number>()
59
+ * .load([['a', 1], ['b', 2], ['c', 3]])
60
+ * .update('a', v => (v ?? 0) + 10)
61
+ * .sortByValues((a, b) => a - b)
62
+ *
63
+ * // Use iter-tools for transformations
64
+ * const doubled = new ExtMap<string, number>()
65
+ * .load(iterMap(([k, v]) => [k, v * 2], extMap))
66
+ *
67
+ * // Use iter-tools for filtering
68
+ * const filtered = new ExtMap<string, number>()
69
+ * .load(filter(([k, v]) => v > 5, extMap))
70
+ * ```
71
+ */
72
+ declare class ExtMap<K = any, V = any> extends View<Map<K, V>> implements Map<K, V> {
73
+ constructor(iterable?: Iterable<readonly [K, V]> | null | undefined);
74
+ constructor(obj?: Record<Extract<K, string>, V>);
75
+ static fromObject<K extends string, V>(obj: Record<K, V>): ExtMap<K, V>;
76
+ static fromIterable<K, V>(entries: Iterable<readonly [K, V]>): ExtMap<K, V>;
77
+ /**
78
+ * Creates a shallow copy of the map.
79
+ *
80
+ * @returns A new ExtMap instance with the same entries
81
+ */
82
+ clone(): ExtMap<K, V>;
83
+ /**
84
+ * Converts the map to a JSON-serializable format.
85
+ *
86
+ * @returns Array of key-value pairs suitable for JSON serialization
87
+ */
88
+ toJSON(): [K, V][];
89
+ /**
90
+ * Custom inspection method for better debugging output.
91
+ *
92
+ * @param _depth - The depth of inspection
93
+ * @param _options - Options for inspection
94
+ * @returns A string representation of the map
95
+ */
96
+ [inspect.custom](_depth: number, _options: InspectOptions): string;
97
+ }
98
+
99
+ /**
100
+ * A WeakMap with automatic timeout-based expiry for entries.
101
+ *
102
+ * Entries are automatically removed after a specified timeout period.
103
+ * Accessing an entry refreshes its timeout, extending its lifetime.
104
+ * This is useful for caching scenarios where you want automatic cleanup
105
+ * of unused entries while keeping frequently accessed ones alive.
106
+ */
107
+ declare class TimeoutWeakMap<K extends object, V> {
108
+ readonly timeoutMs: number;
109
+ protected readonly wmap: WeakMap<K, [V, NodeJS.Timeout]>;
110
+ /**
111
+ * @param timeoutMs Default timeout in milliseconds for entries
112
+ */
113
+ constructor(timeoutMs: number);
114
+ /**
115
+ * Retrieves the value for the given key and refreshes its timeout.
116
+ *
117
+ * @param key The key to retrieve
118
+ * @returns The value if found, undefined otherwise
119
+ */
120
+ get(key: K): V | undefined;
121
+ /**
122
+ * Sets a key-value pair with an optional custom timeout.
123
+ *
124
+ * @param key The key to set
125
+ * @param value The value to associate with the key
126
+ * @param timeoutMs Optional timeout override for this entry
127
+ * @returns This instance for chaining
128
+ */
129
+ set(key: K, value: V, timeoutMs?: number): this;
130
+ /**
131
+ * Removes a key-value pair and clears its timeout.
132
+ *
133
+ * @param key The key to delete
134
+ * @returns True if the key existed and was deleted, false otherwise
135
+ */
136
+ delete(key: K): boolean;
137
+ /**
138
+ * Checks if a key exists in the map.
139
+ * Does not refresh the timeout.
140
+ *
141
+ * @param key The key to check
142
+ * @returns True if the key exists, false otherwise
143
+ */
144
+ has(key: K): boolean;
145
+ /**
146
+ * Loads multiple key-value pairs into the map.
147
+ *
148
+ * @param entries Iterable of key-value pairs to load
149
+ * @param timeoutMs Optional timeout override for all entries
150
+ * @returns This instance for chaining
151
+ */
152
+ load(entries: Iterable<[K, V]>, timeoutMs?: number): this;
153
+ /**
154
+ * Updates an existing value or creates a new one using an update function.
155
+ *
156
+ * @param key The key to update
157
+ * @param update Function that receives the current value and returns the new value
158
+ * @returns This instance for chaining
159
+ */
160
+ update(key: K, update: (value: V | undefined, key: K, map: this) => V): this;
161
+ /**
162
+ * Gets a value or creates it using a factory function if it doesn't exist.
163
+ * Refreshes timeout if the value exists.
164
+ *
165
+ * @param key The key to get or create
166
+ * @param factory Function to create the value if it doesn't exist
167
+ * @param timeoutMs Optional timeout override for new entries
168
+ * @returns The existing or newly created value
169
+ */
170
+ getOrDefault(key: K, factory: (key: K, map: this) => V, timeoutMs?: number): V;
171
+ }
172
+
173
+ type MapKeys = keyof Map<Any, Any>;
174
+ type GenericMap<K, V, P extends MapKeys> = {
175
+ [Method in P]: Method extends 'set' ? (key: K, value: V) => Any : Method extends 'get' ? (key: K) => V | undefined : Method extends 'has' ? (key: K) => boolean : Method extends 'delete' ? (key: K) => boolean : Method extends 'clear' ? () => void : Method extends 'forEach' ? (callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: Any) => void : Method extends 'entries' ? () => IterableIterator<[K, V]> : Method extends 'keys' ? () => IterableIterator<K> : Method extends 'values' ? () => IterableIterator<V> : Method extends typeof Symbol.iterator ? () => IterableIterator<[K, V]> : Method extends 'size' ? number : Method extends typeof Symbol.toStringTag ? string : Any;
176
+ };
177
+
178
+ /**
179
+ * Returns an array of all key-value pairs in the map.
180
+ * Convenience method that converts the entries iterator to an array.
181
+ *
182
+ * @returns Array of all key-value pairs
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * const map = new ExtMap<string, number>()
187
+ * .load([['a', 1], ['b', 2], ['c', 3]])
188
+ *
189
+ * console.log(entriesArray(map)) // [['a', 1], ['b', 2], ['c', 3]]
190
+ * ```
191
+ */
192
+ declare function entriesArray<K, V>(ins: GenericMap<K, V, typeof Symbol.iterator>): [K, V][];
193
+
194
+ /**
195
+ * Checks if the provided value implements the Map interface with the specified required properties.
196
+ */
197
+ declare function isGenericMap<Props extends (keyof Map<K, V>)[], K, V>(target: unknown, requiredProps?: Props): target is Pick<Map<K, V>, Props[number]>;
198
+
199
+ /**
200
+ * Returns an array of all keys in the map.
201
+ * Convenience method that converts the keys iterator to an array.
202
+ *
203
+ * @returns Array of all keys
204
+ *
205
+ * @example
206
+ * ```typescript
207
+ * const map = new ExtMap<string, number>()
208
+ * .load([['a', 1], ['b', 2], ['c', 3]])
209
+ *
210
+ * console.log(keysArray(map)) // ['a', 'b', 'c']
211
+ * ```
212
+ */
213
+ declare function keysArray<K, V>(ins: GenericMap<K, V, 'keys'>): K[];
214
+
215
+ /**
216
+ * Gets a value from a map or creates it using a factory function if it doesn't exist.
217
+ */
218
+ declare function mapGetOrDefault<K, V, T extends GenericMap<K, V, 'get' | 'has' | 'set'>>(map: T, key: K, factory: (key: K, map: T) => V): V;
219
+
220
+ /**
221
+ * Loads multiple entries into the map from an iterable.
222
+ *
223
+ * @param entries - An iterable of key-value pairs to load into the map
224
+ * @returns The map instance for method chaining
225
+ */
226
+ declare function mapLoad<T extends GenericMap<K, V, 'set'>, K, V>(ins: T, entries: Iterable<[K, V]>): T;
227
+
228
+ /**
229
+ * Reverses the order of entries in a Map.
230
+ * @remarks This function creates a new Map with the entries of the original Map in reverse order.
231
+ * The original Map is not modified.
232
+ * @example ```ts
233
+ * mapReverse(new Map([['a', 1], ['b', 2], ['c', 3]]));
234
+ * //=> [['c', 3], ['b', 2], ['a', 1]]
235
+ * ```
236
+ */
237
+ declare function mapReverse<T extends GenericMap<K, V, 'set' | 'clear' | typeof Symbol.iterator>, K, V>(ins: T): T;
238
+ declare function mapReverse<K, V>(ins: Map<K, V>): Map<K, V>;
239
+
240
+ /**
241
+ * Updates a value in the map using an update function.
242
+ *
243
+ * @param key - The key to update
244
+ * @param update - Function that receives the current value and returns the new value
245
+ * @returns The map instance for method chaining
246
+ */
247
+ declare function mapUpdate<T extends GenericMap<K, V, 'set' | 'get'>, K, V>(ins: T, key: K, update: (value: V | undefined, key: K, map: T) => V): T;
248
+ declare function mapUpdate<K, V>(ins: Map<K, V>, key: K, update: (value: V | undefined, key: K, map: Map<K, V>) => V): typeof ins;
249
+
250
+ /**
251
+ * Sorts the map entries using a custom comparison function and updates the map in place.
252
+ * This is Map-specific because it maintains insertion order.
253
+ *
254
+ * @param ins - The map instance to sort
255
+ * @param compare - Function that compares two entries
256
+ * @returns The map instance for method chaining
257
+ *
258
+ * @example
259
+ * ```typescript
260
+ * const map = new ExtMap<string, number>([
261
+ * ['c', 3],
262
+ * ['a', 1],
263
+ * ['b', 2],
264
+ * ])
265
+ *
266
+ * sort(map, ([k1], [k2]) => k1.localeCompare(k2))
267
+ * console.log(entriesArray(map)) // [['a', 1], ['b', 2], ['c', 3]]
268
+ * ```
269
+ */
270
+ declare function sort<K, V>(ins: GenericMap<K, V, 'set' | 'clear' | typeof Symbol.iterator>, compare: (a: [K, V], b: [K, V]) => number): GenericMap<K, V, 'set' | 'clear' | typeof Symbol.iterator>;
271
+
272
+ /**
273
+ * Sorts the map entries by their keys and updates the map in place.
274
+ *
275
+ * @param ins - The map instance to sort
276
+ * @param compare - Function that compares two keys
277
+ * @returns The map instance for method chaining
278
+ *
279
+ * @example
280
+ * ```typescript
281
+ * const map = new ExtMap<string, number>([
282
+ * ['c', 3],
283
+ * ['a', 1],
284
+ * ['b', 2],
285
+ * ])
286
+ *
287
+ * sortByKeys(map, (a, b) => a.localeCompare(b))
288
+ * console.log(entriesArray(map)) // [['a', 1], ['b', 2], ['c', 3]]
289
+ * ```
290
+ */
291
+ declare function sortByKeys<K, V>(ins: GenericMap<K, V, 'set' | 'clear' | typeof Symbol.iterator>, compare: (a: K, b: K) => number): GenericMap<K, V, 'set' | 'clear' | typeof Symbol.iterator>;
292
+
293
+ /**
294
+ * Sorts the map entries by their values and updates the map in place.
295
+ *
296
+ * @param ins - The map instance to sort
297
+ * @param compare - Function that compares two values
298
+ * @returns The map instance for method chaining
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * const map = new ExtMap<string, number>([
303
+ * ['c', 3],
304
+ * ['a', 1],
305
+ * ['b', 2],
306
+ * ])
307
+ *
308
+ * sortByValues(map, (a, b) => a - b)
309
+ * console.log(entriesArray(map)) // [['a', 1], ['b', 2], ['c', 3]]
310
+ * ```
311
+ */
312
+ declare function sortByValues<T extends GenericMap<K, V, 'set' | 'clear' | typeof Symbol.iterator>, K, V>(ins: T, compare: (a: V, b: V) => number): T;
313
+ declare function sortByValues<K, V>(ins: GenericMap<K, V, 'set' | 'clear' | typeof Symbol.iterator>, compare: (a: V, b: V) => number): GenericMap<K, V, 'set' | 'clear' | typeof Symbol.iterator>;
314
+
315
+ /**
316
+ * Converts a GenericMap to a native Map.
317
+ *
318
+ * @param ins - The GenericMap instance to convert
319
+ * @returns A new native Map with the same entries
320
+ *
321
+ * @example
322
+ * ```typescript
323
+ * const extMap = new ExtMap<string, number>()
324
+ * .load([['a', 1], ['b', 2], ['c', 3]])
325
+ *
326
+ * const nativeMap = toMap(extMap)
327
+ * console.log(nativeMap instanceof Map) // true
328
+ * ```
329
+ */
330
+ declare function toMap<K, V>(ins: GenericMap<K, V, typeof Symbol.iterator>): Map<K, V>;
331
+
332
+ /**
333
+ * Returns an array of all values in the map.
334
+ * Convenience method that converts the values iterator to an array.
335
+ *
336
+ * @returns Array of all values
337
+ *
338
+ * @example
339
+ * ```typescript
340
+ * const map = new ExtMap<string, number>()
341
+ * .load([['a', 1], ['b', 2], ['c', 3]])
342
+ *
343
+ * console.log(valuesArray(map)) // [1, 2, 3]
344
+ * ```
345
+ */
346
+ declare function valuesArray<K, V>(ins: GenericMap<K, V, 'values'>): V[];
347
+
348
+ export { ExtMap, type GenericMap, type MapKeys, TimeoutWeakMap, entriesArray, isGenericMap, keysArray, mapGetOrDefault, mapLoad, mapReverse, mapUpdate, sort, sortByKeys, sortByValues, toMap, valuesArray };
package/index.mjs ADDED
@@ -0,0 +1,446 @@
1
+ import { isIterable, map, filter } from 'iter-tools';
2
+ import { inspect } from 'util';
3
+
4
+ var __defProp = Object.defineProperty;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+
7
+ // ../composition/src/View.ts
8
+ var TARGET_SYMBOL = /* @__PURE__ */ Symbol("target");
9
+ var View = class {
10
+ static {
11
+ __name(this, "View");
12
+ }
13
+ [TARGET_SYMBOL];
14
+ constructor(target) {
15
+ this[TARGET_SYMBOL] = target;
16
+ }
17
+ get [Symbol.toStringTag]() {
18
+ return this.constructor.name;
19
+ }
20
+ get target() {
21
+ return this[TARGET_SYMBOL];
22
+ }
23
+ };
24
+
25
+ // ../composition/src/inheritProxifiedPrototypeProperty.ts
26
+ function inheritProxifiedPrototypeProperty(ViewerClass, TargetClass, key) {
27
+ const des = Reflect.getOwnPropertyDescriptor(TargetClass.prototype, key);
28
+ if (!des) {
29
+ return;
30
+ }
31
+ if (des.value && typeof des.value === "function") {
32
+ return Object.defineProperty(ViewerClass.prototype, key, {
33
+ value(...args) {
34
+ return this.target[key](...args);
35
+ },
36
+ writable: true,
37
+ configurable: true,
38
+ enumerable: false
39
+ });
40
+ } else if (des && !des.get && !des.set) {
41
+ return Object.defineProperty(ViewerClass.prototype, key, {
42
+ get() {
43
+ return this.target[key];
44
+ },
45
+ set: des.writable ? /* @__PURE__ */ __name(function set(value) {
46
+ this.target[key] = value;
47
+ }, "set") : void 0,
48
+ configurable: true,
49
+ enumerable: false
50
+ });
51
+ } else {
52
+ Object.defineProperty(ViewerClass.prototype, key, {
53
+ get: des.get ? function() {
54
+ return this.target[key];
55
+ } : void 0,
56
+ set: des.set ? function(value) {
57
+ this.target[key] = value;
58
+ } : void 0,
59
+ configurable: true,
60
+ enumerable: false
61
+ });
62
+ }
63
+ }
64
+ __name(inheritProxifiedPrototypeProperty, "inheritProxifiedPrototypeProperty");
65
+
66
+ // ../composition/src/inheritProxifiedPrototype.ts
67
+ function inheritProxifiedPrototype(ViewerClass, TargetClass, omitKeys) {
68
+ Reflect.ownKeys(TargetClass.prototype).filter((k) => {
69
+ return k !== "constructor" && k !== Symbol.toStringTag;
70
+ }).filter((k) => {
71
+ return omitKeys ? !omitKeys.includes(k) : true;
72
+ }).forEach((k) => {
73
+ return inheritProxifiedPrototypeProperty(ViewerClass, TargetClass, k);
74
+ });
75
+ return ViewerClass;
76
+ }
77
+ __name(inheritProxifiedPrototype, "inheritProxifiedPrototype");
78
+
79
+ // ../object/src/entriesOf.ts
80
+ function entriesOf(obj) {
81
+ return Object.entries(obj);
82
+ }
83
+ __name(entriesOf, "entriesOf");
84
+
85
+ // ../object/src/defineMethod.ts
86
+ function defineMethod(obj, key, value, des = {}) {
87
+ return Object.defineProperty(obj, key, {
88
+ value,
89
+ configurable: true,
90
+ writable: true,
91
+ enumerable: false,
92
+ ...des
93
+ });
94
+ }
95
+ __name(defineMethod, "defineMethod");
96
+ function filterIterable(mapLike, predicate) {
97
+ return filter(([k, v]) => {
98
+ return predicate(v, k);
99
+ }, mapLike);
100
+ }
101
+ __name(filterIterable, "filterIterable");
102
+ function mapIterable(mapLike, transform) {
103
+ return map(([k, v]) => {
104
+ return transform(v, k);
105
+ }, mapLike);
106
+ }
107
+ __name(mapIterable, "mapIterable");
108
+ function mapIterableKeys(mapLike, transform) {
109
+ return map(([k, v]) => {
110
+ return [
111
+ transform(k, v),
112
+ v
113
+ ];
114
+ }, mapLike);
115
+ }
116
+ __name(mapIterableKeys, "mapIterableKeys");
117
+ function mapIterableValues(mapLike, transform) {
118
+ return map(([k, v]) => {
119
+ return [
120
+ k,
121
+ transform(v, k)
122
+ ];
123
+ }, mapLike);
124
+ }
125
+ __name(mapIterableValues, "mapIterableValues");
126
+
127
+ // ../iter/src/reduceIterable.ts
128
+ function reduceIterable(mapLike, reducer, initialValue) {
129
+ for (const [key, value] of mapLike) {
130
+ initialValue = reducer(initialValue, value, key);
131
+ }
132
+ return initialValue;
133
+ }
134
+ __name(reduceIterable, "reduceIterable");
135
+
136
+ // ../iter/src/toObjectIterable.ts
137
+ function toObjectIterable(mapLike) {
138
+ return Object.fromEntries(mapLike);
139
+ }
140
+ __name(toObjectIterable, "toObjectIterable");
141
+
142
+ // src/entriesArray.ts
143
+ function entriesArray(ins) {
144
+ return Array.from(ins);
145
+ }
146
+ __name(entriesArray, "entriesArray");
147
+
148
+ // src/keysArray.ts
149
+ function keysArray(ins) {
150
+ return Array.from(ins.keys());
151
+ }
152
+ __name(keysArray, "keysArray");
153
+
154
+ // src/mapGetOrDefault.ts
155
+ function mapGetOrDefault(map4, key, factory) {
156
+ let value = map4.get(key);
157
+ if (value !== void 0 || map4.has(key)) {
158
+ return value;
159
+ }
160
+ value = factory(key, map4);
161
+ map4.set(key, value);
162
+ return value;
163
+ }
164
+ __name(mapGetOrDefault, "mapGetOrDefault");
165
+
166
+ // src/mapLoad.ts
167
+ function mapLoad(ins, entries) {
168
+ for (const [key, value] of entries) {
169
+ ins.set(key, value);
170
+ }
171
+ return ins;
172
+ }
173
+ __name(mapLoad, "mapLoad");
174
+
175
+ // src/mapReverse.ts
176
+ function mapReverse(ins) {
177
+ const entries = Array.from(ins).reverse();
178
+ ins.clear();
179
+ mapLoad(ins, entries);
180
+ return ins;
181
+ }
182
+ __name(mapReverse, "mapReverse");
183
+
184
+ // src/mapUpdate.ts
185
+ function mapUpdate(ins, key, update) {
186
+ const newValue = update(ins.get(key), key, ins);
187
+ ins.set(key, newValue);
188
+ return ins;
189
+ }
190
+ __name(mapUpdate, "mapUpdate");
191
+
192
+ // src/sort.ts
193
+ function sort(ins, compare) {
194
+ const entries = Array.from(ins).sort(compare);
195
+ ins.clear();
196
+ for (const [k, v] of entries) {
197
+ ins.set(k, v);
198
+ }
199
+ return ins;
200
+ }
201
+ __name(sort, "sort");
202
+
203
+ // src/sortByKeys.ts
204
+ function sortByKeys(ins, compare) {
205
+ const entries = Array.from(ins).sort((a, b) => {
206
+ return compare(a[0], b[0]);
207
+ });
208
+ ins.clear();
209
+ for (const [k, v] of entries) {
210
+ ins.set(k, v);
211
+ }
212
+ return ins;
213
+ }
214
+ __name(sortByKeys, "sortByKeys");
215
+
216
+ // src/sortByValues.ts
217
+ function sortByValues(ins, compare) {
218
+ const entries = Array.from(ins).sort((a, b) => {
219
+ return compare(a[1], b[1]);
220
+ });
221
+ ins.clear();
222
+ for (const [k, v] of entries) {
223
+ ins.set(k, v);
224
+ }
225
+ return ins;
226
+ }
227
+ __name(sortByValues, "sortByValues");
228
+
229
+ // src/toMap.ts
230
+ function toMap(ins) {
231
+ return new Map(ins);
232
+ }
233
+ __name(toMap, "toMap");
234
+
235
+ // src/valuesArray.ts
236
+ function valuesArray(ins) {
237
+ return Array.from(ins.values());
238
+ }
239
+ __name(valuesArray, "valuesArray");
240
+
241
+ // src/ExtMap.ts
242
+ var ExtMap = class _ExtMap extends View {
243
+ static {
244
+ __name(this, "ExtMap");
245
+ }
246
+ constructor(arg) {
247
+ super(new Map(isIterable(arg) ? arg : arg ? entriesOf(arg) : void 0));
248
+ }
249
+ static fromObject(obj) {
250
+ return new _ExtMap(entriesOf(obj));
251
+ }
252
+ static fromIterable(entries) {
253
+ return new _ExtMap(entries);
254
+ }
255
+ /**
256
+ * Creates a shallow copy of the map.
257
+ *
258
+ * @returns A new ExtMap instance with the same entries
259
+ */
260
+ clone() {
261
+ return new _ExtMap(this);
262
+ }
263
+ /**
264
+ * Converts the map to a JSON-serializable format.
265
+ *
266
+ * @returns Array of key-value pairs suitable for JSON serialization
267
+ */
268
+ toJSON() {
269
+ return [
270
+ ...this.entries()
271
+ ];
272
+ }
273
+ /**
274
+ * Custom inspection method for better debugging output.
275
+ *
276
+ * @param _depth - The depth of inspection
277
+ * @param _options - Options for inspection
278
+ * @returns A string representation of the map
279
+ */
280
+ [inspect.custom](_depth, _options) {
281
+ return inspect(this.target, {
282
+ breakLength: 50
283
+ });
284
+ }
285
+ };
286
+ function thisify(fn) {
287
+ return function(...args) {
288
+ return fn(this, ...args);
289
+ };
290
+ }
291
+ __name(thisify, "thisify");
292
+ function transformReturnValue(fn, transform) {
293
+ return function(...args) {
294
+ const result = fn.apply(this, args);
295
+ return transform(result);
296
+ };
297
+ }
298
+ __name(transformReturnValue, "transformReturnValue");
299
+ inheritProxifiedPrototype(ExtMap, Map, []);
300
+ defineMethod(ExtMap.prototype, "load", thisify(mapLoad));
301
+ defineMethod(ExtMap.prototype, "sort", thisify(sort));
302
+ defineMethod(ExtMap.prototype, "sortByKeys", thisify(sortByKeys));
303
+ defineMethod(ExtMap.prototype, "sortByValues", thisify(sortByValues));
304
+ defineMethod(ExtMap.prototype, "reverse", thisify(mapReverse));
305
+ defineMethod(ExtMap.prototype, "update", thisify(mapUpdate));
306
+ defineMethod(ExtMap.prototype, "getOrDefault", thisify(mapGetOrDefault));
307
+ defineMethod(ExtMap.prototype, "keysArray", thisify(keysArray));
308
+ defineMethod(ExtMap.prototype, "valuesArray", thisify(valuesArray));
309
+ defineMethod(ExtMap.prototype, "entriesArray", thisify(entriesArray));
310
+ defineMethod(ExtMap.prototype, "toMap", thisify(toMap));
311
+ defineMethod(ExtMap.prototype, "toObject", thisify(toObjectIterable));
312
+ defineMethod(ExtMap.prototype, "reduce", thisify(reduceIterable));
313
+ defineMethod(ExtMap.prototype, "map", thisify(transformReturnValue(mapIterable, ExtMap.fromIterable)));
314
+ defineMethod(ExtMap.prototype, "mapKeys", thisify(transformReturnValue(mapIterableKeys, ExtMap.fromIterable)));
315
+ defineMethod(ExtMap.prototype, "mapValues", thisify(transformReturnValue(mapIterableValues, ExtMap.fromIterable)));
316
+ defineMethod(ExtMap.prototype, "filter", thisify(transformReturnValue(filterIterable, ExtMap.fromIterable)));
317
+
318
+ // src/TimeoutWeakMap.ts
319
+ var TimeoutWeakMap = class {
320
+ static {
321
+ __name(this, "TimeoutWeakMap");
322
+ }
323
+ timeoutMs;
324
+ wmap = /* @__PURE__ */ new WeakMap();
325
+ /**
326
+ * @param timeoutMs Default timeout in milliseconds for entries
327
+ */
328
+ constructor(timeoutMs) {
329
+ this.timeoutMs = timeoutMs;
330
+ }
331
+ /**
332
+ * Retrieves the value for the given key and refreshes its timeout.
333
+ *
334
+ * @param key The key to retrieve
335
+ * @returns The value if found, undefined otherwise
336
+ */
337
+ get(key) {
338
+ const vt = this.wmap.get(key);
339
+ if (!vt) {
340
+ return void 0;
341
+ }
342
+ const [value, timeout] = vt;
343
+ timeout.refresh();
344
+ return value;
345
+ }
346
+ /**
347
+ * Sets a key-value pair with an optional custom timeout.
348
+ *
349
+ * @param key The key to set
350
+ * @param value The value to associate with the key
351
+ * @param timeoutMs Optional timeout override for this entry
352
+ * @returns This instance for chaining
353
+ */
354
+ set(key, value, timeoutMs) {
355
+ this.wmap.set(key, [
356
+ value,
357
+ setTimeout(() => {
358
+ this.delete(key);
359
+ }, timeoutMs ?? this.timeoutMs).unref()
360
+ ]);
361
+ return this;
362
+ }
363
+ /**
364
+ * Removes a key-value pair and clears its timeout.
365
+ *
366
+ * @param key The key to delete
367
+ * @returns True if the key existed and was deleted, false otherwise
368
+ */
369
+ delete(key) {
370
+ const vt = this.wmap.get(key);
371
+ if (!vt) {
372
+ return false;
373
+ }
374
+ const timeout = vt[1];
375
+ clearTimeout(timeout);
376
+ return this.wmap.delete(key);
377
+ }
378
+ /**
379
+ * Checks if a key exists in the map.
380
+ * Does not refresh the timeout.
381
+ *
382
+ * @param key The key to check
383
+ * @returns True if the key exists, false otherwise
384
+ */
385
+ has(key) {
386
+ return this.wmap.has(key);
387
+ }
388
+ /**
389
+ * Loads multiple key-value pairs into the map.
390
+ *
391
+ * @param entries Iterable of key-value pairs to load
392
+ * @param timeoutMs Optional timeout override for all entries
393
+ * @returns This instance for chaining
394
+ */
395
+ load(entries, timeoutMs) {
396
+ for (const [key, value] of entries) {
397
+ this.set(key, value, timeoutMs);
398
+ }
399
+ return this;
400
+ }
401
+ /**
402
+ * Updates an existing value or creates a new one using an update function.
403
+ *
404
+ * @param key The key to update
405
+ * @param update Function that receives the current value and returns the new value
406
+ * @returns This instance for chaining
407
+ */
408
+ update(key, update) {
409
+ return this.set(key, update(this.get(key), key, this));
410
+ }
411
+ /**
412
+ * Gets a value or creates it using a factory function if it doesn't exist.
413
+ * Refreshes timeout if the value exists.
414
+ *
415
+ * @param key The key to get or create
416
+ * @param factory Function to create the value if it doesn't exist
417
+ * @param timeoutMs Optional timeout override for new entries
418
+ * @returns The existing or newly created value
419
+ */
420
+ getOrDefault(key, factory, timeoutMs) {
421
+ const vt = this.wmap.get(key);
422
+ if (vt) {
423
+ const [value, timeout] = vt;
424
+ timeout.refresh();
425
+ return value;
426
+ } else {
427
+ const value = factory(key, this);
428
+ this.set(key, value, timeoutMs);
429
+ return value;
430
+ }
431
+ }
432
+ };
433
+
434
+ // src/isGenericMap.ts
435
+ function isGenericMap(target, requiredProps = [
436
+ "get",
437
+ "set",
438
+ "has"
439
+ ]) {
440
+ return !!target && requiredProps.every((prop) => {
441
+ return typeof target[prop] === typeof Map.prototype[prop];
442
+ });
443
+ }
444
+ __name(isGenericMap, "isGenericMap");
445
+
446
+ export { ExtMap, TimeoutWeakMap, entriesArray, isGenericMap, keysArray, mapGetOrDefault, mapLoad, mapReverse, mapUpdate, sort, sortByKeys, sortByValues, toMap, valuesArray };
package/package.json CHANGED
@@ -1,14 +1,26 @@
1
1
  {
2
2
  "name": "@bemoje/map",
3
- "version": "0.2.1",
4
- "type": "commonjs",
5
- "main": "cjs/index.js",
6
- "types": "cjs/index.d.ts",
3
+ "version": "1.0.0",
4
+ "description": "map",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "keywords": [
8
+ "map"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "types": "./index.d.ts",
13
+ "import": "./index.mjs",
14
+ "default": "./index.mjs"
15
+ }
16
+ },
7
17
  "dependencies": {
8
- "tslib": "latest"
18
+ "iter-tools": "^7.5.4"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
9
22
  },
10
23
  "license": "MIT",
11
- "keywords": [],
12
24
  "author": {
13
25
  "name": "Benjamin Møller Jensen",
14
26
  "email": "bemoje@bemoje.net",
@@ -16,14 +28,7 @@
16
28
  },
17
29
  "repository": {
18
30
  "type": "git",
19
- "url": "git+https://github.com/bemoje/tsmono.git"
20
- },
21
- "funding": {
22
- "type": "patreon",
23
- "url": "https://www.patreon.com/user?u=40752770"
24
- },
25
- "bugs": {
26
- "url": "https://github.com/bemoje/tsmono/issues"
27
- },
28
- "homepage": "https://github.com/bemoje/tsmono"
31
+ "url": "git+https://github.com/bemoje/mono.git",
32
+ "directory": "libs/map"
33
+ }
29
34
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 Benjamin Møller Jensen
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
@@ -1,34 +0,0 @@
1
- # @bemoje/map
2
-
3
-
4
-
5
- ![npm (scoped)](https://img.shields.io/npm/v/%40bemoje/trie-map)
6
- ![npm bundle size (scoped)](https://img.shields.io/bundlephobia/minzip/%40bemoje/map)
7
- ![npm](https://img.shields.io/npm/dt/%40bemoje/map)
8
- ![NPM](https://img.shields.io/npm/l/%40bemoje%2Fmap)
9
-
10
- ![GitHub last commit (by committer)](https://img.shields.io/github/last-commit/bemoje/tsmono)
11
- ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/bemoje/tsmono)
12
- ![GitHub top language](https://img.shields.io/github/languages/top/bemoje/tsmono)
13
-
14
-
15
- ## Documentation
16
- [Documentation Website](https://bemoje.github.io/tsmono/modules/map.html)
17
-
18
- ## Installation
19
- This library is published in the NPM registry and can be installed using any compatible package manager.
20
-
21
- #### NPM
22
- ```sh
23
- npm install @bemoje/map
24
- ```
25
-
26
-
27
- ## Issues
28
- Please let me know of any bugs or [issues](https://github.com/bemoje/tsmono/issues).
29
-
30
- ## Contribute
31
- Contributors are welcome to open a [pull request](https://github.com/bemoje/tsmono/pulls).
32
-
33
- ## License
34
- Released under the [undefined License](./LICENSE).
package/cjs/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from './lib/mapGetOrElse';
2
- export * from './lib/mapReverse';
3
- export * from './lib/mapUpdate';
4
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../packages/map/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,oBAAoB,CAAA;AAClC,cAAc,kBAAkB,CAAA;AAChC,cAAc,iBAAiB,CAAA"}
package/cjs/index.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- tslib_1.__exportStar(require("./lib/mapGetOrElse"), exports);
5
- tslib_1.__exportStar(require("./lib/mapReverse"), exports);
6
- tslib_1.__exportStar(require("./lib/mapUpdate"), exports);
7
- //# sourceMappingURL=index.js.map
package/cjs/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../packages/map/src/index.ts"],"names":[],"mappings":";;;AAAA,6DAAkC;AAClC,2DAAgC;AAChC,0DAA+B"}
@@ -1,15 +0,0 @@
1
- /**
2
- * Returns a value from a map, while setting a given default value before returning it, if the key is not present.
3
- * @param map map to get value from
4
- * @param key key to get value for
5
- * @param callback callback to set the value if key is not present
6
- * @template K - The type of the keys in the Map.
7
- * @returns The value retrieved from the Map or generated by the callback function.
8
- * @example ```ts
9
- * const map = new Map<string, number>()
10
- * map.set('key', 1)
11
- * mapGetOrElse(map, 'nonexistentKey', () => 2) // Output: 2
12
- * ```
13
- */
14
- export declare function mapGetOrElse<K, V>(map: Map<K, V>, key: K, callback: (key: K) => V): V;
15
- //# sourceMappingURL=mapGetOrElse.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mapGetOrElse.d.ts","sourceRoot":"","sources":["../../../../../packages/map/src/lib/mapGetOrElse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAMrF"}
@@ -1,26 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mapGetOrElse = void 0;
4
- /**
5
- * Returns a value from a map, while setting a given default value before returning it, if the key is not present.
6
- * @param map map to get value from
7
- * @param key key to get value for
8
- * @param callback callback to set the value if key is not present
9
- * @template K - The type of the keys in the Map.
10
- * @returns The value retrieved from the Map or generated by the callback function.
11
- * @example ```ts
12
- * const map = new Map<string, number>()
13
- * map.set('key', 1)
14
- * mapGetOrElse(map, 'nonexistentKey', () => 2) // Output: 2
15
- * ```
16
- */
17
- function mapGetOrElse(map, key, callback) {
18
- let value = map.get(key);
19
- if (value !== undefined)
20
- return value;
21
- value = callback(key);
22
- map.set(key, value);
23
- return value;
24
- }
25
- exports.mapGetOrElse = mapGetOrElse;
26
- //# sourceMappingURL=mapGetOrElse.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mapGetOrElse.js","sourceRoot":"","sources":["../../../../../packages/map/src/lib/mapGetOrElse.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;GAYG;AACH,SAAgB,YAAY,CAAO,GAAc,EAAE,GAAM,EAAE,QAAuB;IAChF,IAAI,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IACxB,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAA;IACrC,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAA;IACrB,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IACnB,OAAO,KAAK,CAAA;AACd,CAAC;AAND,oCAMC"}
@@ -1,15 +0,0 @@
1
- /**
2
- * Reverses the order of entries in a Map.
3
- * @remarks This function creates a new Map with the entries of the original Map in reverse order.
4
- * The original Map is not modified.
5
- * @typeparam K - The type of the keys in the Map.
6
- * @typeparam V - The type of the values in the Map.
7
- * @param map The Map to reverse.
8
- * @returns A new Map with the entries of the original Map in reverse order.
9
- * @example ```ts
10
- * mapReverse(new Map([['a', 1], ['b', 2], ['c', 3]]));;
11
- * //=> [['c', 3], ['b', 2], ['a', 1]]
12
- * ```
13
- */
14
- export declare function mapReverse<K, V>(map: Map<K, V>): Map<K, V>;
15
- //# sourceMappingURL=mapReverse.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mapReverse.d.ts","sourceRoot":"","sources":["../../../../../packages/map/src/lib/mapReverse.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAE1D"}
@@ -1,21 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mapReverse = void 0;
4
- /**
5
- * Reverses the order of entries in a Map.
6
- * @remarks This function creates a new Map with the entries of the original Map in reverse order.
7
- * The original Map is not modified.
8
- * @typeparam K - The type of the keys in the Map.
9
- * @typeparam V - The type of the values in the Map.
10
- * @param map The Map to reverse.
11
- * @returns A new Map with the entries of the original Map in reverse order.
12
- * @example ```ts
13
- * mapReverse(new Map([['a', 1], ['b', 2], ['c', 3]]));;
14
- * //=> [['c', 3], ['b', 2], ['a', 1]]
15
- * ```
16
- */
17
- function mapReverse(map) {
18
- return new Map([...map.entries()].reverse());
19
- }
20
- exports.mapReverse = mapReverse;
21
- //# sourceMappingURL=mapReverse.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mapReverse.js","sourceRoot":"","sources":["../../../../../packages/map/src/lib/mapReverse.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;GAYG;AACH,SAAgB,UAAU,CAAO,GAAc;IAC7C,OAAO,IAAI,GAAG,CAAO,CAAC,GAAG,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC,OAAO,EAAE,CAAC,CAAA;AACpD,CAAC;AAFD,gCAEC"}
@@ -1,20 +0,0 @@
1
- /**
2
- * Updates the value for the given key in the map using the provided function.
3
- * If the key does not exist in the map, the function will be called with `undefined` as the value.
4
- * @template K - The type of the keys in the map.
5
- * @param map - The map to update.
6
- * @param key - The key of the value to update.
7
- * @param fun - The function to use to update the value.
8
- * This function takes the current value (or `undefined` if the key does not exist) and the key as arguments,
9
- * and should return the new value.
10
- * @returns - The new value for the key.
11
- * @example ```ts
12
- * const map = new Map<string, number>()
13
- * map.set('a', 1)
14
- * mapUpdate(map, 'a', (value, key) => value !== undefined ? value + 1 : 0)
15
- * map.get('a')
16
- * //=> 2
17
- * ```
18
- */
19
- export declare function mapUpdate<K, V>(map: Map<K, V>, key: K, fun: (value: V | undefined, key: K) => V): V;
20
- //# sourceMappingURL=mapUpdate.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mapUpdate.d.ts","sourceRoot":"","sources":["../../../../../packages/map/src/lib/mapUpdate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,KAAK,EAAE,CAAC,GAAG,SAAS,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAInG"}
@@ -1,28 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mapUpdate = void 0;
4
- /**
5
- * Updates the value for the given key in the map using the provided function.
6
- * If the key does not exist in the map, the function will be called with `undefined` as the value.
7
- * @template K - The type of the keys in the map.
8
- * @param map - The map to update.
9
- * @param key - The key of the value to update.
10
- * @param fun - The function to use to update the value.
11
- * This function takes the current value (or `undefined` if the key does not exist) and the key as arguments,
12
- * and should return the new value.
13
- * @returns - The new value for the key.
14
- * @example ```ts
15
- * const map = new Map<string, number>()
16
- * map.set('a', 1)
17
- * mapUpdate(map, 'a', (value, key) => value !== undefined ? value + 1 : 0)
18
- * map.get('a')
19
- * //=> 2
20
- * ```
21
- */
22
- function mapUpdate(map, key, fun) {
23
- const value = fun(map.get(key), key);
24
- map.set(key, value);
25
- return value;
26
- }
27
- exports.mapUpdate = mapUpdate;
28
- //# sourceMappingURL=mapUpdate.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mapUpdate.js","sourceRoot":"","sources":["../../../../../packages/map/src/lib/mapUpdate.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,SAAgB,SAAS,CAAO,GAAc,EAAE,GAAM,EAAE,GAAwC;IAC9F,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAA;IACpC,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IACnB,OAAO,KAAK,CAAA;AACd,CAAC;AAJD,8BAIC"}