diff options
author | Joris | 2020-02-03 18:28:50 +0100 |
---|---|---|
committer | Joris | 2020-02-03 18:28:50 +0100 |
commit | cbcc269be607cc964fbd69d179d8a0e8b8e4bffa (patch) | |
tree | 7a8135f7ede7e1ff02bc1cf1d697a8c39a56e962 /src/number.ts | |
parent | c7e20a6dd01a2ae049c451d18511708aaee60a19 (diff) |
Extract dom and number utilities to external files
Diffstat (limited to 'src/number.ts')
-rw-r--r-- | src/number.ts | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/src/number.ts b/src/number.ts new file mode 100644 index 0000000..3021dc9 --- /dev/null +++ b/src/number.ts @@ -0,0 +1,91 @@ +import { h } from './dom' + +export interface Parsed { + before: string; + number: number; + after: string; +} + +export function parse(str: string): Parsed | undefined { + let start; + for (start = 0; start < str.length; start++) { + if (isDigit(str.charAt(start))) { + break + } + } + + if (start === str.length) { + return undefined + } + + // Integer part + let integerPart = ''; + let end = start; + for (; end < str.length; end++) { + const c = str.charAt(end) + + if (!isDigit(c)) { + break + } else { + integerPart += c + } + } + + // Decimal sign + if (end < str.length && (str.charAt(end) === '.' || str.charAt(end) === ',')) { + end++ + } + + // Decimal part + let decimalPart = ''; + for (; end < str.length; end++) { + const c = str.charAt(end) + + if (!isDigit(c)) { + break + } else { + decimalPart += c + } + } + + + return { + before: str.substring(0, start), + number: parseFloat(integerPart + (decimalPart !== '' ? '.' + decimalPart : '')), + after: str.substring(end, str.length) + } +} + +function isDigit(c: string) { + return c >= '0' && c <= '9' +} + +export interface Node { + node: Element; + number: HTMLInputElement; +} + +export function node(tag: string, parsedNumber: Parsed): Node { + const numberElement = h( + 'input', + { + 'class': 'g-Number', + 'value': prettyPrint(parsedNumber.number) + } + ) as HTMLInputElement + + return { + node: h(tag, {}, [parsedNumber.before, numberElement, parsedNumber.after]), + number: numberElement, + } +} + +export function prettyPrint(n: number): string { + const xs = n.toString().split('.') + + if (xs.length == 2) { + return xs[0] + ',' + xs[1].substring(0, 2) + } else { + return xs[0] + } +} |