format.ts
72 lines
| 1.9 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r55 | import { format as dojoFormatNumber } from "dojo/number"; | ||
| import { format as dojoFormatDate } from "dojo/date/locale"; | ||||
|
|
r65 | import { Formatter, compile as _compile } from "./StringFormat"; | ||
|
|
r55 | |||
|
|
r115 | import { isNumber, isNull, get } from "../safe"; | ||
|
|
r55 | |||
| interface NumberFormatOptions { | ||||
| round?: number; | ||||
| pattern?: string; | ||||
| } | ||||
|
|
r115 | function convertNumber(value: any, _pattern?: string) { | ||
|
|
r55 | if (isNumber(value)) { | ||
| const nopt = {} as NumberFormatOptions; | ||||
|
|
r115 | let pattern = _pattern; | ||
| if (pattern && pattern.indexOf("!") === 0) { | ||||
|
|
r55 | nopt.round = -1; | ||
| pattern = pattern.substr(1); | ||||
| } | ||||
| nopt.pattern = pattern; | ||||
| return dojoFormatNumber(value, nopt); | ||||
|
|
r115 | } else { | ||
| return ""; | ||||
|
|
r55 | } | ||
| } | ||||
|
|
r115 | function convertDate(value: any, pattern?: string) { | ||
|
|
r55 | if (value instanceof Date) { | ||
|
|
r115 | const m = pattern && pattern.match(/^(\w+)-(\w+)$/); | ||
|
|
r55 | if (m) | ||
| return dojoFormatDate(value, { | ||||
| selector: m[2], | ||||
| formatLength: m[1] | ||||
| }); | ||||
| else if (pattern === "iso") | ||||
| return value.toISOString(); | ||||
| else | ||||
| return dojoFormatDate(value, { | ||||
| selector: "date", | ||||
| datePattern: pattern | ||||
| }); | ||||
|
|
r115 | } else { | ||
| return ""; | ||||
|
|
r55 | } | ||
| } | ||||
| const _formatter = new Formatter([convertNumber, convertDate]); | ||||
|
|
r65 | function format(msg: string, ...args: any[]) { | ||
| return _formatter.format(msg, ...args); | ||||
| } | ||||
|
|
r115 | function _convert(value: any, pattern?: string) { | ||
|
|
r65 | return _formatter.convert(value, pattern); | ||
| } | ||||
| namespace format { | ||||
| export const convert = _convert; | ||||
| export function compile(text: string) { | ||||
| const template = _compile(text); | ||||
|
|
r115 | return (...data: any[]) => { | ||
|
|
r65 | return template((name, pattern) => { | ||
|
|
r115 | const value = get(name, data); | ||
|
|
r65 | return !isNull(value) ? convert(value, pattern) : ""; | ||
| }); | ||||
| }; | ||||
| } | ||||
| } | ||||
| export = format; | ||||
