Ver Fonte

feature: object for each

xiongxt há 1 ano atrás
pai
commit
0bd40cabf6
2 ficheiros alterados com 30 adições e 0 exclusões
  1. 29 0
      sdk/async.ts
  2. 1 0
      sdk/unitOfWork.ts

+ 29 - 0
sdk/async.ts

@@ -37,3 +37,32 @@ export function nextTick(time = 0) {
     }, time);
   });
 }
+
+export function objectForEach<O extends Record<PropertyKey, unknown>>(
+  obj: O,
+  callback: (value: O[keyof O], key: PropertyKey) => void
+) {
+  const keys = Reflect.ownKeys(obj);
+  keys.forEach((key) => {
+    callback(Reflect.get(obj, key), key);
+  });
+}
+
+export async function asyncObjectForEach<
+  O extends Record<PropertyKey, unknown>
+>(
+  obj: O,
+  callback: (value: O[keyof O], key: PropertyKey) => boolean | Promise<boolean>
+) {
+  const keys = Reflect.ownKeys(obj);
+  let index = 0;
+  const newCallback = async () => {
+    const key = keys[index];
+    const res = await callback(Reflect.get(obj, key), key);
+    if (index < keys.length - 1 && res !== false) {
+      index++;
+      await newCallback();
+    }
+  };
+  return await newCallback();
+}

+ 1 - 0
sdk/unitOfWork.ts

@@ -0,0 +1 @@
+function loop() {}