Skip to content

Commit

Permalink
feat(strings): add charRange(), add radix & zero-pad presets
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Sep 10, 2019
1 parent ae1ec8d commit c9e5a63
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/strings/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from "./pad-right";
export * from "./parse";
export * from "./percent";
export * from "./radix";
export * from "./range";
export * from "./repeat";
export * from "./slugify";
export * from "./splice";
Expand Down
15 changes: 15 additions & 0 deletions packages/strings/src/pad-left.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,18 @@ export const padLeft: (
? ((x = x.toString()), x.length < n ? buf.substr(x.length) + x : x)
: buf;
});

/**
* Zero-padded 2 digit formatter.
*/
export const Z2 = padLeft(2, "0");

/**
* Zero-padded 3 digit formatter.
*/
export const Z3 = padLeft(3, "0");

/**
* Zero-padded 4 digit formatter.
*/
export const Z4 = padLeft(4, "0");
10 changes: 10 additions & 0 deletions packages/strings/src/radix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ export const radix: (
*/
export const B8 = radix(2, 8);

/**
* 16bit binary conversion preset.
*/
export const B16 = radix(2, 16);

/**
* 32bit binary conversion preset.
*/
export const B32 = radix(2, 32);

/**
* 8bit hex conversion preset.
* Assumes unsigned inputs.
Expand Down
20 changes: 20 additions & 0 deletions packages/strings/src/range.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Yields iterator of characters [`from`..`to`] (inclusive). Uses
* reverse ordering if `to` < `from`.
*
* @param from
* @param to
*/
export function* charRange(from: string | number, to: string | number) {
let i = typeof from === "string" ? from.charCodeAt(0) : from;
const end = typeof to === "string" ? to.charCodeAt(0) : to;
if (i <= end) {
for (; i <= end; i++) {
yield String.fromCharCode(i);
}
} else {
for (; i >= end; i--) {
yield String.fromCharCode(i);
}
}
}

0 comments on commit c9e5a63

Please sign in to comment.