Skip to content

[Feature] Add cpad function to stdlib.text #1038

@ajwalkiewicz

Description

@ajwalkiewicz

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

  1. 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.
  2. To not build it on top of lpad and rpad, but that I'm afraid would duplicate the logic from those functions anyway.

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibRelated to Amber's Standard Library

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions