Skip to content

Commit

Permalink
Add Array.pad (#3660)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexGeb authored and tim-smart committed Oct 6, 2024
1 parent dc97f64 commit fc44692
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/tall-vans-appear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": minor
---

Add Array.pad function
33 changes: 33 additions & 0 deletions packages/effect/src/Array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1758,6 +1758,39 @@ export const copy: {
<A>(self: ReadonlyArray<A>): Array<A>
} = (<A>(self: ReadonlyArray<A>): Array<A> => 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: {
<A, T>(
n: number,
fill: T
): (
self: Array<A>
) => Array<A | T>
<A, T>(self: Array<A>, n: number, fill: T): Array<A | T>
} = dual(3, <A, T>(self: Array<A>, n: number, fill: T): Array<A | T> => {
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
Expand Down
8 changes: 8 additions & 0 deletions packages/effect/test/Array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]])
Expand Down

0 comments on commit fc44692

Please sign in to comment.