amber-lang / amber

💎 Amber the programming language compiled to bash
https://amber-lang.com
GNU General Public License v3.0
3.8k stars 80 forks source link

[Feature] Add more string functions in stdlib #328

Closed Mte90 closed 1 month ago

Mte90 commented 1 month ago

What do you think to add this functions?

pub fun to_string(value): Text {
    if {
        value is Text: return "{value}"
        value is Num: {
            return unsafe $ echo "{value}" $
            }
        value is [Text] or value is [Num]: return  unsafe $ IFS="" ; echo "\$\{{nameof value}[*]}" $
    }
    return ""
}

pub fun floor(value:Num): Num {
    return unsafe parse(replace(to_string(value), ".*", ""))
}

pub fun slice(string: Text, index:Num, length:Num): Text {
    index = floor(index)
    length  = floor(length)
    return unsafe $ echo "\$\{string:index:length}" $
}

pub fun char_at(string: Text, index:Num): Text {
    return slice(string, index, 1)
}

pub fun capitalize(string: Text): Text {
    let first_char = char_at(string, 0)
    let rest = slice(string,1, len(string))
    return upper(first_char) + rest
}

pub fun rpad(string: Text, pad:Text, value:Num): Text {
    if len(string) >= value: return string
    if len(pad) > 1: pad = char_at(pad,0)
    let adjoin = value - len(string)
    string = string + repeat(pad, adjoin)
    return string
}

pub fun lpad(string: Text, pad:Text, value:Num): Text {
    if len(string) >= value: return string
    if len(pad) > 1: pad = char_at(pad,0)
    let adjoin = value - len(string)
    string = repeat(pad, adjoin) + string
    return string
}
CymDeveloppement commented 1 month ago

Why to_string() ? as Text not work ? for the other text functions, maybe printf do that with one line of code.

Mte90 commented 1 month ago

Maybe we can think to a proposal that use printf? I think that those functions can be very useful for scripting.

Ph0enixKM commented 1 month ago

@Mte90 I think that if we add floor then we need to add ceil as well. It's easy to implement since ceil is just floor() + 1.

round should also appear in the PR.

KrosFire commented 1 month ago

I'd like to also see regex searches with =~ operator. It will be more complicated and will require heavy testing, but I think it's very useful.

Mte90 commented 1 month ago

I'd like to also see regex searches with =~ operator. It will be more complicated and will require heavy testing, but I think it's very useful.

Indeed but I think that regex as they can be very complicated it is the case for phase 2 when we finished with the basic set of functions for strings/text.

So we need to find someone that want to improve that code and propose the one with the various new functions.

Mte90 commented 1 month ago

maybe @MuhamedMagdi want to try to do the missing functions

MuhamedMagdi commented 1 month ago

maybe @MuhamedMagdi want to try to do the missing functions

Sure, I can give it a shot!