Skip to content

Commit

Permalink
feat: add padStart and padEnd to String
Browse files Browse the repository at this point in the history
  • Loading branch information
brekk committed Apr 18, 2024
1 parent 82c427b commit 40f11be
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
36 changes: 36 additions & 0 deletions prelude/__internal__/String.mad
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,42 @@ export repeat = (c, n) => pipe(
fromList,
)(n)

/**
* Pad the beginning of a string with a character up to a specific limit
* @since 0.23.8
* @example
* padStart('-', 3, ">") // "-->"
* padStart('-', 3, "cool") // "cool"
*/
padStart :: Char -> Integer -> String -> String
export padStart = (pre, count, str) => {
len = length(str)
return if (len > count) {
str
} else do {
prefix = repeat(pre, count - len)
return prefix ++ str
}
}

/**
* Pad the end of a string with a character up to a specific limit
* @since 0.23.8
* @example
* padEnd('-', 3, "<") // "<--"
* padEnd('-', 3, "cool") // "cool"
*/
padEnd :: Char -> Integer -> String -> String
export padEnd = (post, count, str) => {
len = length(str)
return if (len > count) {
str
} else do {
suffix = repeat(post, count - len)
return str ++ suffix
}
}


#iftarget js

Expand Down
16 changes: 16 additions & 0 deletions prelude/__internal__/String.spec.mad
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,19 @@ test("contains - false", () => assertEquals(String.contains("aü", "abüc"), fal
test("endsWith - true", () => assertEquals(String.endsWith("c", "abüc"), true))
test("endsWith - utf8", () => assertEquals(String.endsWith("üc", "abüc"), true))
test("endsWith - false", () => assertEquals(String.endsWith("bü", "abüc"), false))

test(
"padStart",
() => do {
_ <- assertEquals(String.padStart('-', 3, ">"), "-->")
return assertEquals(String.padStart('-', 3, "cool"), "cool")
},
)

test(
"padEnd",
() => do {
_ <- assertEquals(String.padEnd('-', 3, "<"), "<--")
return assertEquals(String.padEnd('-', 3, "cool"), "cool")
},
)

0 comments on commit 40f11be

Please sign in to comment.