updated trimming methods for string
no more "// lol" anymore
#[no_std, cache_output]
+trim = (
+ string: @string,
+ tokens: @string | [@string],
+ left: @bool = false,
+ right: @bool = false,
+){
+ token_check = token => token.length > 0
+ let tokens = switch tokens {
+ [@string]: tokens.filter(token_check),
+ @string: tokens.split('').filter(token_check),
+ }
+ if tokens.length == 0 {return string}
+ let start = 0
+ let end = string.length
+ if left {
+ for i in ..string.length {
+ if tokens.contains(string[i]) {
+ start = i+1
+ } else {break}
+ }
+ }
+ if right {
+ for i in (string.length)..0 {
+ if tokens.contains(string[i]) {
+ end = i
+ } else {break}
+ }
+ }
+ return $.substr(string, start, end) if start < end else ""
+}
+
impl @string {
is_empty: #[desc("Returns true if the string has a length of 0, false otherwise") example("
$.assert(''.is_empty())
@@ -104,32 +135,8 @@ str2 = ' pog __'
$.assert(str1.l_trim() == 'abcd g ')
$.assert(str2.l_trim() == 'pog __')
")]
- (self, tokens: @string | [@string] = [' ', '\n']) {
- // check for tokens
- for token in tokens {
- if token.length != 1 {
- throw "Trim tokens must all be 1-character long"
- }
- }
-
- let tokenlist = tokens
- if tokens.type == @string {
- tokenlist = [tokens]
- }
-
- // scan left
- let begin = 0
-
- for i in ..self.length {
- if tokenlist.contains(self[i]) {
- continue
- } else {
- begin = i
- break
- }
- }
-
- return $.substr(self, begin, self.length)
+ (self, tokens: @string | [@string] = [' ','\n','\t','\r']) {
+ return trim(self, tokens, left = true)
},
r_trim: #[desc("Returns a right-trimmed version of the string") example("
str = 'abcd '
@@ -139,8 +146,8 @@ $.assert(str.r_trim() == 'abcd')
$.assert(str2.r_trim() == ' abcd g')
$.assert(str3.r_trim(tokens = [' ', '_']) == ' pog')
")]
- (self, tokens: @string | [@string] = [' ', '\n']) {
- return self.reverse().l_trim(tokens).reverse() // lol
+ (self, tokens: @string | [@string] = [' ','\n','\t','\r']) {
+ return trim(self, tokens, right = true)
},
trim: #[desc("Returns a trimmed version of the string") example("
str = 'abcd '
@@ -150,8 +157,8 @@ $.assert(str.trim() == 'abcd')
$.assert(str2.trim() == 'abcd g')
$.assert(str3.trim(tokens = [' ', '_']))
")]
- (self, tokens: @string | [@string] = [' ', '\n']){
- return self.l_trim(tokens).r_trim(tokens)
+ (self, tokens: @string | [@string] = [' ','\n','\t','\r']){
+ return trim(self, tokens, left = true, right = true)
},
fmt: #[desc("Returns a formtted version of the string. Accepts either a single argument or an array") example("
name1 = 'bob'
