small optimization
Massimo Melina committed
Apr 4, 2025 at 09:46 UTC
c79872f36fa84f3f832d02a336f63d1a1d5a4183
1 file changed
+13
-10
src/cross.ts
+13
-10
@@ -264,28 +264,31 @@ export function findDefined<I, O>(a: I[] | Record<string, I>, cb:(v:I, k: string
264
}
265
}
266
267
+// create new object with values returned by callback. Keys are kept the same unless you call `setK('myKey')`. Calling `setK` without parameters, which implies `undefined`, will remove the key.
268
export function newObj<S extends (object | undefined | null),VR=unknown>(
269
src: S,
270
returnNewValue: (value: S[keyof S], key: Exclude<keyof S, symbol>, setK:(newK?: string)=>true, depth: number) => any,
270
- recur: boolean | number=false
271
+ recur: boolean | number=false // recur on the returned value, if it's an object
272
) {
272
- const pairs = Object.entries(src || {}).map( ([k,v]) => {
273
- if (typeof k === 'symbol') return
274
- let _k: undefined | typeof k = k
273
+ let _k: undefined | string
274
+ const entries = Object.entries(src || {}).map( ([k,v]) => {
275
const curDepth = typeof recur === 'number' ? recur : 0
276
- let newV = returnNewValue(v, k as Exclude<keyof S, symbol>, (newK) => {
277
- _k = newK
278
- return true // for convenient expression concatenation
279
- }, curDepth)
276
+ _k = k
277
+ let newV = returnNewValue(v, k as Exclude<keyof S, symbol>, setK, curDepth)
278
if ((recur !== false || returnNewValue.length === 4) // if callback is using depth parameter, then it wants recursion
279
&& _.isPlainObject(newV)) // is it recurrable?
280
newV = newObj(newV, returnNewValue, curDepth + 1)
281
return _k !== undefined && [_k, newV]
282
})
285
- return Object.fromEntries(onlyTruthy(pairs)) as S extends undefined | null ? S : { [K in keyof S]:VR }
283
+ return Object.fromEntries(onlyTruthy(entries)) as S extends undefined | null ? S : { [K in keyof S]:VR }
284
+
285
+ function setK(newK: typeof _k) { // declare once (optimization)
286
+ _k = newK
287
+ return true as const // for convenient expression concatenation: setK('newK') && 'newValue'
288
+ }
289
}
290
288
-// returns undefined if timeout is reached
291
+// returns undefined if timeout is reached, otherwise the value returned by the callback
292
export async function waitFor<T>(cb: ()=> Promisable<T>, { interval=200, timeout=Infinity }={}) {
293
const started = Date.now()
294
while (1) {