diff options
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] + } +} |