Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make List.repeatWith and List.range generic #145

Merged
merged 1 commit into from
Apr 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions prelude/__internal__/List.mad
Original file line number Diff line number Diff line change
Expand Up @@ -115,24 +115,26 @@ 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
range :: (Comparable n, Number n) => n -> n -> List n
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
Loading