From fc4469287ea2c84e39794c34e92c92339ce35437 Mon Sep 17 00:00:00 2001 From: Alexandre Behaghel Date: Thu, 3 Oct 2024 11:46:09 +0200 Subject: [PATCH] Add `Array.pad` (#3660) --- .changeset/tall-vans-appear.md | 5 +++++ packages/effect/src/Array.ts | 33 ++++++++++++++++++++++++++++++ packages/effect/test/Array.test.ts | 8 ++++++++ 3 files changed, 46 insertions(+) create mode 100644 .changeset/tall-vans-appear.md diff --git a/.changeset/tall-vans-appear.md b/.changeset/tall-vans-appear.md new file mode 100644 index 00000000000..048f9cda92f --- /dev/null +++ b/.changeset/tall-vans-appear.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Add Array.pad function diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index 334cbbfb191..0b5ddf7fada 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -1758,6 +1758,39 @@ export const copy: { (self: ReadonlyArray): Array } = ((self: ReadonlyArray): Array => self.slice()) as any +/** + * Pads an array. + * Returns a new array of length `n` with the elements of `array` followed by `fill` elements if `array` is shorter than `n`. + * If `array` is longer than `n`, the returned array will be a slice of `array` containing the `n` first elements of `array`. + * If `n` is less than or equal to 0, the returned array will be an empty array. + * + * @example + * import { Array } from "effect" + * + * const arr = [1, 2, 3] + * const result = Array.pad(arr, 6, 0) + * assert.deepStrictEqual(result, [1, 2, 3, 0, 0, 0]) + * + * @since 3.8.4 + */ +export const pad: { + ( + n: number, + fill: T + ): ( + self: Array + ) => Array + (self: Array, n: number, fill: T): Array +} = dual(3, (self: Array, n: number, fill: T): Array => { + if (self.length >= n) { + return take(self, n) + } + return appendAll( + self, + makeBy(n - self.length, () => fill) + ) +}) + /** * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of * the `Iterable`. Note that `chunksOf(n)([])` is `[]`, not `[[]]`. This is intentional, and is consistent with a recursive diff --git a/packages/effect/test/Array.test.ts b/packages/effect/test/Array.test.ts index 6b1e4bc910e..e1c8e1f80da 100644 --- a/packages/effect/test/Array.test.ts +++ b/packages/effect/test/Array.test.ts @@ -1084,6 +1084,14 @@ describe("ReadonlyArray", () => { deepStrictEqual(pipe([1, 2, 3], RA.chop((as) => [as[0] * 2, as.slice(1)])), [2, 4, 6]) }) + it("pad", () => { + deepStrictEqual(pipe([], RA.pad(0, 0)), []) + deepStrictEqual(pipe([1, 2, 3], RA.pad(0, 0)), []) + deepStrictEqual(pipe([1, 2, 3], RA.pad(2, 0)), [1, 2]) + deepStrictEqual(pipe([1, 2, 3], RA.pad(6, 0)), [1, 2, 3, 0, 0, 0]) + deepStrictEqual(pipe([1, 2, 3], RA.pad(-2, 0)), []) + }) + describe("chunksOf", () => { it("should split a `ReadonlyArray` into length-n pieces", () => { deepStrictEqual(RA.chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]])