2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-03-15 12:02:38 -04:00
|
|
|
|
|
|
|
/** FillOption Object */
|
|
|
|
export interface FillOption {
|
|
|
|
/** Char to fill in */
|
2019-04-05 00:23:05 -04:00
|
|
|
char?: string;
|
2019-03-15 12:02:38 -04:00
|
|
|
/** Side to fill in */
|
2019-04-05 00:23:05 -04:00
|
|
|
side?: "left" | "right";
|
2019-03-15 12:02:38 -04:00
|
|
|
/** If strict, output string can't be greater than strLen*/
|
|
|
|
strict?: boolean;
|
|
|
|
/** char/string used to specify the string has been truncated */
|
|
|
|
strictChar?: string;
|
|
|
|
/** Side of truncate */
|
|
|
|
strictSide?: "left" | "right";
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Pad helper for strings.
|
|
|
|
* Input string is processed to output a string with a minimal length.
|
|
|
|
* If the parameter `strict` is set to true, the output string length
|
|
|
|
* is equal to the `strLen` parameter.
|
|
|
|
* Example:
|
|
|
|
*
|
2019-04-04 05:58:16 -04:00
|
|
|
* pad("deno", 6, { char: "*", side: "left" }) // output : "**deno"
|
|
|
|
* pad("deno", 6, { char: "*", side: "right"}) // output : "deno**"
|
|
|
|
* pad("denosorusrex", 6 {
|
|
|
|
* char: "*",
|
|
|
|
* side: "left",
|
|
|
|
* strict: true,
|
|
|
|
* strictSide: "right",
|
|
|
|
* strictChar: "..."
|
|
|
|
* }) // output : "den..."
|
2019-03-15 12:02:38 -04:00
|
|
|
*
|
|
|
|
* @param input Input string
|
|
|
|
* @param strLen Output string lenght
|
|
|
|
* @param opts Configuration object
|
|
|
|
* @param [opts.char=" "] Character used to fill in
|
|
|
|
* @param [opts.side="left"] Side to fill in
|
|
|
|
* @param [opts.strict=false] Flag to truncate the string if length > strLen
|
|
|
|
* @param [opts.strictChar=""] Character to add if string is truncated
|
|
|
|
* @param [opts.strictSide="right"] Side to truncate
|
|
|
|
*/
|
|
|
|
export function pad(
|
|
|
|
input: string,
|
|
|
|
strLen: number,
|
|
|
|
opts: FillOption = {
|
|
|
|
char: " ",
|
|
|
|
strict: false,
|
|
|
|
side: "left",
|
|
|
|
strictChar: "",
|
|
|
|
strictSide: "right"
|
|
|
|
}
|
|
|
|
): string {
|
|
|
|
let out = input;
|
|
|
|
const outL = out.length;
|
|
|
|
if (outL < strLen) {
|
2019-04-05 00:23:05 -04:00
|
|
|
if (!opts.side || opts.side === "left") {
|
2019-03-15 12:02:38 -04:00
|
|
|
out = out.padStart(strLen, opts.char);
|
|
|
|
} else {
|
|
|
|
out = out.padEnd(strLen, opts.char);
|
|
|
|
}
|
|
|
|
} else if (opts.strict && outL > strLen) {
|
2019-10-05 12:02:34 -04:00
|
|
|
const addChar = opts.strictChar ? opts.strictChar : "";
|
2019-03-15 12:02:38 -04:00
|
|
|
if (opts.strictSide === "left") {
|
|
|
|
let toDrop = outL - strLen;
|
|
|
|
if (opts.strictChar) {
|
|
|
|
toDrop += opts.strictChar.length;
|
|
|
|
}
|
|
|
|
out = `${addChar}${out.slice(toDrop, outL)}`;
|
|
|
|
} else {
|
|
|
|
out = `${out.substring(0, strLen - addChar.length)}${addChar}`;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return out;
|
|
|
|
}
|