Skip to content

Commit

Permalink
feat(stdlib): add new functions in std/text (#373)
Browse files Browse the repository at this point in the history
* feat(stdlib): add new functions in `std/text`

- `reverse`: reverses the given text.
- `is_prefix`: checks if a string is a prefix of another string.
- `is_suffix`: checks if a string is a suffix of another string.

These addition of `is_prefix` & `is_suffix` complement the existing `contains` function.

* refactor: change `is_prefix` & `is_suffix` function names

is_prefix -> starts_with
is_suffix -> ends_with
  • Loading branch information
MuhamedMagdi committed Jul 31, 2024
1 parent 03c7705 commit 71224ec
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/std/text.ab
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,26 @@ pub fun contains(text: Text, phrase: Text): Bool {

return result == "1"
}

/// Reverse a text using `rev`
pub fun reverse(text: Text): Text {
return unsafe $echo "{text}" | rev$
}

/// Check if text starts with a value
pub fun starts_with(text: Text, prefix: Text): Bool {
let result = unsafe $if [[ "{text}" == "{prefix}"* ]]; then
echo 1
fi$

return result == "1"
}

/// Check if text ends with a value
pub fun ends_with(text: Text, suffix: Text): Bool {
let result = unsafe $if [[ "{text}" == *"{suffix}" ]]; then
echo 1
fi$

return result == "1"
}
7 changes: 7 additions & 0 deletions src/tests/stdlib/ends_with.ab
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import * from "std/text"

main {
if ends_with("hello world", "world") {
echo "Succeded"
}
}
8 changes: 8 additions & 0 deletions src/tests/stdlib/reverse.ab
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import * from "std/text"

// Output
// dlrow olleh

main {
echo reverse("hello world")
}
7 changes: 7 additions & 0 deletions src/tests/stdlib/starts_with.ab
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import * from "std/text"

main {
if starts_with("hello world", "hello") {
echo "Succeded"
}
}

0 comments on commit 71224ec

Please sign in to comment.