Skip to content

Commit

Permalink
Merge pull request #1921 from o1-labs/features/arrays/pad_zip
Browse files Browse the repository at this point in the history
[easy] Added `zip` and `pad` functionalities for arrays
  • Loading branch information
querolita authored Nov 27, 2024
2 parents 37ae603 + 2b528e9 commit fa205aa
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions src/lib/util/arrays.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { assert } from './errors.js';

export { chunk, chunkString };
export { chunk, chunkString, zip, pad };

function chunk<T>(array: T[], size: number): T[][] {
assert(array.length % size === 0, 'invalid input length');
assert(
array.length % size === 0,
`chunk(): invalid input length, it must be a multiple of ${size}`
);
return Array.from({ length: array.length / size }, (_, i) =>
array.slice(size * i, size * (i + 1))
);
Expand All @@ -12,3 +15,19 @@ function chunk<T>(array: T[], size: number): T[][] {
function chunkString(str: string, size: number): string[] {
return chunk([...str], size).map((c) => c.join(''));
}

function zip<T, S>(a: T[], b: S[]) {
assert(
a.length <= b.length,
'zip(): second array must be at least as long as the first array'
);
return a.map((a, i): [T, S] => [a, b[i]!]);
}

function pad<T>(array: T[], size: number, value: T): T[] {
assert(
array.length <= size,
`target size ${size} should be greater or equal than the length of the array ${array.length}`
);
return array.concat(Array.from({ length: size - array.length }, () => value));
}

0 comments on commit fa205aa

Please sign in to comment.