Let's Refactor Some JS: Blockstack Todos Example

in javascript •  7 years ago 

So, I was checking out Blockstack's Todo list example, and one code snippet stuck out to me that it could be dramatically improved in readability if rewritten with modern JS.

Before:

fetchData () {
  const blockstack = this.blockstack
  blockstack.getFile(STORAGE_FILE)
  .then((todosText) => {
    var todos = JSON.parse(todosText || '[]')
    todos.forEach(function (todo, index) {
      todo.id = index
    })
    this.uidCount = todos.length
    this.todos = todos
  })
},

After:

async fetchData () {
  const todosText = await this.blockstack.getFile(STORAGE_FILE)
  const todos = JSON.parse(todosText || '[]')
  this.todos = todos.map((todo, id) => ({...todo, id}))
  this.uidCount = todos.length
},

As far as ESNext features go, I used async/await, object spread, fat arrow implicit return, and object property shorthand.

Also, stylistically, there's no need to reassign this.blockstack, it's not used again, and it doesn't make the code shorter. Further, the map method is much better for this function, for many reasons. (FP technique primarily)

Finally the order in which uidCount is assigned the length of todos doesn't matter much, nor does which todos array I use to assign that value.

If anyone notices this code isn't functionally equivalent, let me know. I've had a fair amount of mead tonight.

Thanks for reading! This is my first post on Steemit, just sharing my JS knowledge, and maybe tomorrow I'll open up a PR to contribute the code back to the community. That said, they were using Node 6, not Node 8, so some of these newer features might not be welcome additions to the codebase.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!