Skip to content

Commit

Permalink
feat: make repeatWith generic
Browse files Browse the repository at this point in the history
  • Loading branch information
brekk committed Mar 31, 2024
1 parent cbc6824 commit cc84c61
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
9 changes: 5 additions & 4 deletions prelude/__internal__/List.mad
Original file line number Diff line number Diff line change
Expand Up @@ -115,24 +115,25 @@ export repeat = (a, count) => count <= 0 ? [] : [a, ...repeat(a, count - 1)]
* @example
* repeatWith((i) => show(i), 3) // ["0", "1", "2"]
*/
repeatWith :: (Integer -> a) -> Integer -> List a

repeatWith :: (Comparable n, Number n) => (n -> a) -> n -> List a
export repeatWith = (f, count) => {
helper :: (Comparable n, Number n) => n -> a
helper = (index) => index >= count ? [] : [f(index), ...helper(index + 1)]

return helper(0)
}


/**
* Return a list of integers within the given range. The start
* Return a list of numbers within the given range. The start
* parameter is inclusive and the end parameter is exclusive.
*
* @since 0.12.0
* @example
* range(3, 3) // []
* range(3, 5) // [3, 4]
* range(3_s, 6_s) // [3_s, 4_s, 5_s]
*/
range :: Integer -> Integer -> List Integer
export range = (start, end) => repeatWith((i) => i + start, end - start)


Expand Down
3 changes: 3 additions & 0 deletions prelude/__internal__/List.spec.mad
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,9 @@ test("takeWhile", () => assertEquals(takeWhile((x) => x < 5, [1, 2, 3, 4, 5, 6])
test("reverse", () => assertEquals(reverse([1, 2, 3]), [3, 2, 1]))

test("range", () => assertEquals(range(3, 7), [3, 4, 5, 6]))
test("range - short", () => assertEquals(range(3_s, 7_s), [3_s, 4_s, 5_s, 6_s]))
test("range - float", () => assertEquals(range(3.0, 7.0), [3.0, 4.0, 5.0, 6.0]))
test("range - byte", () => assertEquals(range(3_b, 7_b), [3_b, 4_b, 5_b, 6_b]))

test("range - same start and end", () => assertEquals(range(3, 3), []))

Expand Down

0 comments on commit cc84c61

Please sign in to comment.