Skip to content

Commit

Permalink
feat(date): add defTimecode() formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Sep 20, 2020
1 parent c8e84ad commit 42753e1
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions packages/date/src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,55 @@ export const FMT_hms = defFormat(["h", ":", "mm", ":", "ss", " ", "A"]);
*/
// prettier-ignore
export const FMT_yyyyMMdd_HHmmss = defFormat(["yyyy", "MM", "dd", "-", "HH", "mm", "ss"]);

/**
* Returns a time formatter for given FPS (frames / second, in [1..100] range),
* e.g. `HH:mm:ss:ff`. The returned function takes a single arg (time in
* milliseconds) and returns formatted string.
*
* @remarks
* The timecode considers days too, but only includes them in the result if the
* day part is non-zero. The 4 separators between each field can be customized
* via 2nd arg (default: all `:`).
*
* @example
* ```ts
* a = defTimecode(30);
* a(HOUR + 2*MINUTE + 3*SECOND + 4*1000/30)
* // "01:02:03:04"
*
* a(DAY);
* // "01:00:00:00:00"
*
* b = defTimecode(30, ["d ", "h ", "' ", '" ']);
* b(Day + HOUR + 2*MINUTE + 3*SECOND + 999)
* // "01d 01h 02' 03" 29"
* ```
*
* @param fps
* @param sep
*/
export const defTimecode = (fps: number, sep: ArrayLike<string> = "::::") => {
const frame = 1000 / fps;
return (t: number) => {
const d = (t / DAY) | 0;
t -= d * DAY;
const h = (t / HOUR) | 0;
t -= h * HOUR;
const m = (t / MINUTE) | 0;
t -= m * MINUTE;
const s = (t / SECOND) | 0;
t -= s * SECOND;
const parts = [
Z2(h),
sep[1],
Z2(m),
sep[2],
Z2(s),
sep[3],
Z2((t / frame) | 0),
];
d > 0 && parts.unshift(`${Z2(d)}${sep[0]}`);
return parts.join("");
};
};

0 comments on commit 42753e1

Please sign in to comment.