From 71224ec3f0df11ead53e610f673e1021224f8a6d Mon Sep 17 00:00:00 2001 From: Mohamed Magdi Date: Wed, 31 Jul 2024 04:37:47 +0300 Subject: [PATCH] feat(stdlib): add new functions in `std/text` (#373) * 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 --- src/std/text.ab | 23 +++++++++++++++++++++++ src/tests/stdlib/ends_with.ab | 7 +++++++ src/tests/stdlib/reverse.ab | 8 ++++++++ src/tests/stdlib/starts_with.ab | 7 +++++++ 4 files changed, 45 insertions(+) create mode 100644 src/tests/stdlib/ends_with.ab create mode 100644 src/tests/stdlib/reverse.ab create mode 100644 src/tests/stdlib/starts_with.ab diff --git a/src/std/text.ab b/src/std/text.ab index 670ea28c..fc1d4c47 100644 --- a/src/std/text.ab +++ b/src/std/text.ab @@ -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" +} diff --git a/src/tests/stdlib/ends_with.ab b/src/tests/stdlib/ends_with.ab new file mode 100644 index 00000000..c483b66f --- /dev/null +++ b/src/tests/stdlib/ends_with.ab @@ -0,0 +1,7 @@ +import * from "std/text" + +main { + if ends_with("hello world", "world") { + echo "Succeded" + } +} diff --git a/src/tests/stdlib/reverse.ab b/src/tests/stdlib/reverse.ab new file mode 100644 index 00000000..c0f78aad --- /dev/null +++ b/src/tests/stdlib/reverse.ab @@ -0,0 +1,8 @@ +import * from "std/text" + +// Output +// dlrow olleh + +main { + echo reverse("hello world") +} diff --git a/src/tests/stdlib/starts_with.ab b/src/tests/stdlib/starts_with.ab new file mode 100644 index 00000000..103888aa --- /dev/null +++ b/src/tests/stdlib/starts_with.ab @@ -0,0 +1,7 @@ +import * from "std/text" + +main { + if starts_with("hello world", "hello") { + echo "Succeded" + } +}