aboutsummaryrefslogtreecommitdiff
path: root/src/number.ts
blob: 3021dc9cb343a21f2a567a5380f1df05e141b096 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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]
  }
}