|
7 | 7 | } from "o1js";
|
8 | 8 |
|
9 | 9 | import { TypedClass } from "./types";
|
| 10 | +import _ from "lodash"; |
10 | 11 |
|
11 | 12 | export function requireTrue(
|
12 | 13 | condition: boolean,
|
@@ -68,6 +69,26 @@ export function reduceSequential<T, U>(
|
68 | 69 | );
|
69 | 70 | }
|
70 | 71 |
|
| 72 | +export function yieldSequential<Source, State, Target>( |
| 73 | + array: Source[], |
| 74 | + callbackfn: ( |
| 75 | + previousValue: State, |
| 76 | + currentValue: Source, |
| 77 | + currentIndex: number, |
| 78 | + array: Source[] |
| 79 | + ) => Promise<[State, Target]>, |
| 80 | + initialValue: State |
| 81 | +): Promise<[State, Target[]]> { |
| 82 | + return reduceSequential<Source, [State, Target[]]>( |
| 83 | + array, |
| 84 | + async ([state, collectedTargets], curr, index, arr) => { |
| 85 | + const [newState, addition] = await callbackfn(state, curr, index, arr); |
| 86 | + return [newState, collectedTargets.concat(addition)]; |
| 87 | + }, |
| 88 | + [initialValue, []] |
| 89 | + ); |
| 90 | +} |
| 91 | + |
71 | 92 | export function mapSequential<T, R>(
|
72 | 93 | array: T[],
|
73 | 94 | f: (element: T, index: number, array: T[]) => Promise<R>
|
@@ -194,3 +215,39 @@ export function safeParseJson<T>(json: string) {
|
194 | 215 | // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
|
195 | 216 | return JSON.parse(json) as T;
|
196 | 217 | }
|
| 218 | + |
| 219 | +export function isFull<T>(t: Partial<T>): t is T { |
| 220 | + return Object.values(t).findIndex((v) => v === undefined) === -1; |
| 221 | +} |
| 222 | + |
| 223 | +// TODO Restructure utils into separate package and multiple files |
| 224 | + |
| 225 | +export function padArray<T>( |
| 226 | + batch: T[], |
| 227 | + batchSize: number, |
| 228 | + generator: (index: number) => T |
| 229 | +): T[] { |
| 230 | + const slice = batch.slice(); |
| 231 | + const dummies = range(0, batchSize - (batch.length % batchSize)).map((i) => |
| 232 | + generator(i + batch.length) |
| 233 | + ); |
| 234 | + slice.push(...dummies); |
| 235 | + return slice; |
| 236 | +} |
| 237 | + |
| 238 | +export function batch<T>( |
| 239 | + arr: T[], |
| 240 | + batchSize: number, |
| 241 | + dummy: (index: number) => T |
| 242 | +): T[][] { |
| 243 | + const padded = padArray(arr, batchSize, dummy); |
| 244 | + |
| 245 | + const partitioned = _.groupBy( |
| 246 | + padded.map((v, i) => [v, i] as const), |
| 247 | + ([v, i]) => Math.floor(i / batchSize) |
| 248 | + ); |
| 249 | + |
| 250 | + const numBatches = Math.floor(arr.length / batchSize); |
| 251 | + |
| 252 | + return range(0, numBatches).map((i) => partitioned[i].map((x) => x[0])); |
| 253 | +} |
0 commit comments