Skip to content

Commit

Permalink
fix(strings): buffer length (for null inputs) (center())
Browse files Browse the repository at this point in the history
- also truncate oversized inputs
  • Loading branch information
postspectacular committed Aug 9, 2018
1 parent 1a20bc2 commit 5209c42
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions packages/strings/src/center.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,35 @@ import { memoizeJ } from "@thi.ng/memoize/memoizej";

import { Stringer } from "./api";
import { repeat } from "./repeat";
import { truncate } from "./truncate";

/**
* @param n target length
* Returns stringer which pads given input with `ch` (default: space) on
* both sides and returns fixed width string of given `lineWidth`.
* Returns string of only pad characters for any `null` or `undefined`
* values. If the string version of an input is > `lineWidth`, no
* centering is performed, but the string will be truncated to
* `lineWidth`.
*
* Note: The padding string can contain multiple characters.
*
* ```
* center(20, "<>")(wrap(" ")("thi.ng"))
* // "<><><> thi.ng <><><>"
* ```
*
* @param lineWidth target length
* @param ch pad character(s)
*/
export const center: (n: number, ch?: string | number) => Stringer<any> =
export const center: (lineWidth: number, ch?: string | number) => Stringer<any> =
memoizeJ<number, string, Stringer<any>>((n, ch = " ") => {
const buf = repeat(ch, ((n + 1) & ~1) / 2);
const buf = repeat(ch, n);
return (x: any) => {
if (x == null) return buf;
x = x.toString();
const r = (n - x.length) / 2;
return x.length < n ?
buf.substr(0, r) + x + buf.substr(0, r + ((n & 1) === (x.length & 1) ? 0 : 1)) :
x;
truncate(n)(x);
}
});

0 comments on commit 5209c42

Please sign in to comment.