-
Notifications
You must be signed in to change notification settings - Fork 112
Open
Labels
stdlibRelated to Amber's Standard LibraryRelated to Amber's Standard Library
Description
Problem
Centering a text requires writing own custom function, I realized than when I wanted to create a nicely looking separators for the console output of my script, for example:
======== Stage 1 ========
# scrip does some action
======== Stage 2 ========
# another, etc.
Proposal
I propose a simple cpad function that is build on top of lpad and rpad:
/// Pads `text` with the specified `pad` character to the center within the desired `length`
///
/// ### Usage
/// ```ab
/// let padded: Text
///
/// padded = cpad("42", "0", 5)
/// echo padded // "04200"
///
/// padded = cpad("42", "0", 6)
/// echo padded // "004200"
///
/// padded = cpad("42", "0", 1)
/// echo padded // "42"
/// ```
pub fun cpad(text: Text, pad: Text, length: Int): Text {
const text_length = len(text)
if length <= text_length: return text
const left_padding_length = length / 2 + text_length / 2
const left_padded = lpad(text, pad, left_padding_length)
const center_padded = rpad(left_padded, pad, length)
return center_padded
}
Alternatives
- Alternative is to not have it. It is rather nice to have feature not must have. Some languages don't have such feature, e.g. Java, though they are popular libraries that allows that. On the other hand some popular scripting languages like Python or Ruby have it, so I would opt for having it too.
- To not build it on top of
lpadandrpad, but that I'm afraid would duplicate the logic from those functions anyway.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
stdlibRelated to Amber's Standard LibraryRelated to Amber's Standard Library