js1k.js 1.49 KB
Newer Older
Evan Hahn's avatar
Evan Hahn committed
1 2
/*
 * b = body
3 4
 * c = columns
 * d = re-render
Evan Hahn's avatar
Evan Hahn committed
5 6 7
 * g = new column
 * h = new row
 * p = data types
8 9
 * r = rows
 * t = <table>
Evan Hahn's avatar
Evan Hahn committed
10 11
 */

12
/* eslint-disable no-undef */
Evan Hahn's avatar
Evan Hahn committed
13

14
// Data types
Evan Hahn's avatar
Evan Hahn committed
15

16 17 18 19
p = [
  ['text', String],
  ['number', parseFloat],
  ['int', parseInt]
Evan Hahn's avatar
Evan Hahn committed
20
]
Evan Hahn's avatar
Evan Hahn committed
21

22
// Initial data
23

24 25 26
c = [
  ['Minute', p[2]],
  ['Price', p[2]]
27
]
28 29 30 31
r = Array(10).fill(0).map((_, index) => ([
  index + 1,
  Math.random() * 1000
]))
Evan Hahn's avatar
Evan Hahn committed
32

Evan Hahn's avatar
Evan Hahn committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
// Add a new column

g = () => {
  c.push(['Column', p[0]])
  r.map((row) => {
    row.push('')
  })
  d()
}

// Add a new row

h = () => {
  r.push(Array(c.length).fill(null))
  d()
}

50
// Initial render
Evan Hahn's avatar
Evan Hahn committed
51

Evan Hahn's avatar
Evan Hahn committed
52
document.head.innerHTML += '<style>td,th{padding:1em;border:1px solid #000}.b{cursor:pointer;background:#ddf}input{font:inherit;width:100px}</style>'
Evan Hahn's avatar
Evan Hahn committed
53

54
b.innerHTML += '<table id=t style="font-family:sans-serif;border-collapse:collapse">'
Evan Hahn's avatar
Evan Hahn committed
55

56
// Re-render
Evan Hahn's avatar
Evan Hahn committed
57

58 59
;(d = () => {
  let head = document.createElement('tr')
Evan Hahn's avatar
Evan Hahn committed
60 61
  c.map((column, columnIndex) => {
    head.innerHTML += `<th><input value="${column[0]}" onblur=c(this,${columnIndex})> (${column[1][0]})`
62
  })
Evan Hahn's avatar
Evan Hahn committed
63
  head.innerHTML += '<th class=b onclick=g()>+'
Evan Hahn's avatar
Evan Hahn committed
64

65 66
  t.innerHTML = ''
  t.appendChild(head)
Evan Hahn's avatar
Evan Hahn committed
67

68 69 70 71 72 73 74 75 76 77
  r.map((row, index) => {
    let rowEl = document.createElement('tr')
    row.map((cellValue, columnIndex) => {
      rowEl.innerHTML += `<td>${c[columnIndex][1][1](cellValue)}`
    })
    if (!index) {
      rowEl.innerHTML += `<td rowspan=${r.length}>`
    }
    t.appendChild(rowEl)
  })
Evan Hahn's avatar
Evan Hahn committed
78

Evan Hahn's avatar
Evan Hahn committed
79
  t.innerHTML += `<tr><th class=b colspan=${c.length} onclick=h()>+</th><td>`
80
})()