Skip to content

Commit

Permalink
feat: add Array.prototype.chain_
Browse files Browse the repository at this point in the history
  • Loading branch information
tdreyno committed Jan 8, 2021
1 parent 3221e37 commit 7a1a7ae
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/__tests__/util.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,12 @@ describe("mapToIndexedObject", () => {
})
})
})

describe("Array.prototype.chain_", () => {
test("should allow Array chaining", () => {
const sum = (arr: number[]) => arr.reduce((a, b) => a + b, 0)
const result = [1, 2, 3].chain_(sum)

expect(result).toEqual(6)
})
})
13 changes: 13 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,16 @@ export const pairsToIndexedObject = <V, R extends { [key: string]: V }>(
sum: R,
[key, value]: [string, V],
): R => (((sum as { [key: string]: V })[key] = value), sum)

declare global {
interface Array<T> {
chain_<U>(fn: (arr: Array<T>) => U): U
}
}

Array.prototype.chain_ = function <T, U>(
this: Array<T>,
fn: (arr: Array<T>) => U,
): U {
return fn(this)
}

0 comments on commit 7a1a7ae

Please sign in to comment.