Comment

Comment by chrismorgan

A comment on code organisation.

https://github.com/victorqribeiro/TinyApp/blob/db92225cfd0ae...:

  export default function Input(state) {

      const inp = input({  // ①
          type: 'number', value: state.count, onchange
      })

      function update() {  // ②
          inp.value = state.count
      }

      function onchange() {  // ③
          state.count = parseInt(this.value)
      }

      state.addUpdate('count', update)  // ④

      return inp
  }
(Labelling comments mine.)

This ordering isn’t great: ① refers to ③, and ④ refers to ②. It’d be better to reorder them, at least to swap ② and ③, and remove the blank line separating ② and ④:

  export default function Input(state) {
      const inp = input({  // ①
          type: 'number', value: state.count, onchange
      })

      function onchange() {  // ③
          state.count = parseInt(this.value)
      }

      function update() {  // ②
          inp.value = state.count
      }
      state.addUpdate('count', update)  // ④

      return inp
  }
But you really can do much better:

  export default function Input(state) {
      const inp = input({
          type: 'number',
          value: state.count,
          onchange() {
              state.count = parseInt(this.value)
          }
      })

      state.addUpdate('count', function() {
          inp.value = state.count
      })

      return inp
  }
At least at this scale, that’s much easier to follow.

Inlining can improve other places too (though at larger scales it becomes more debatable):

  export default function Button(state) {
      return button({
          onclick() {
              state.count += 1
          },
          style: {
              color: 'black',
              border: 'solid 1px black'
          },
      }, '+ 1')
  }

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton