uncategorized

Fun with Node 4.0 and ES6

I am really liking the ES6 features added to the latest node version.

Here is an example.

I have a result set which in an array of hashes. Each hash has an attribute client_os.
I would like to have a sorted array of the unique values for client_os.

###The record set (results)

1
[ { ct: 7, client_os: 'Android', year: 2015, day: 251 },
  { ct: 26, client_os: 'OS X', year: 2015, day: 251 },
  { ct: 114, client_os: 'Windows', year: 2015, day: 251 },
  { ct: 40, client_os: 'iOS', year: 2015, day: 251 },
  { ct: 14, client_os: 'Android', year: 2015, day: 252 },
  { ct: 36, client_os: 'OS X', year: 2015, day: 252 },
  { ct: 167, client_os: 'Windows', year: 2015, day: 252 },
  { ct: 72, client_os: 'iOS', year: 2015, day: 252 },
  { ct: 5, client_os: 'unknown', year: 2015, day: 252 },
  { ct: 12, client_os: 'Android', year: 2015, day: 253 },
  { ct: 2, client_os: 'Linux', year: 2015, day: 253 },
  { ct: 36, client_os: 'OS X', year: 2015, day: 253 },
  { ct: 168, client_os: 'Windows', year: 2015, day: 253 },
  { ct: 64, client_os: 'iOS', year: 2015, day: 253 },
  { ct: 6, client_os: 'unknown', year: 2015, day: 253 },
  { ct: 13, client_os: 'Android', year: 2015, day: 254 },
  { ct: 2, client_os: 'Linux', year: 2015, day: 254 },
  { ct: 40, client_os: 'OS X', year: 2015, day: 254 },
  { ct: 172, client_os: 'Windows', year: 2015, day: 254 },
  { ct: 63, client_os: 'iOS', year: 2015, day: 254 },
  { ct: 7, client_os: 'unknown', year: 2015, day: 254 },
  { ct: 12, client_os: 'Android', year: 2015, day: 255 },
  { ct: 30, client_os: 'OS X', year: 2015, day: 255 },
  { ct: 128, client_os: 'Windows', year: 2015, day: 255 },
  { ct: 65, client_os: 'iOS', year: 2015, day: 255 },
  { ct: 4, client_os: 'unknown', year: 2015, day: 255 } ]

Using the added functionality of arrow functions and sets the code is quite simple:

  1. Use reduce to iterate over the array
  2. Poplulate a set within the iteration
  3. Convert the set back to an array so it can be sorted
  4. Sort

The code

1
let aKeys = Array.from(results.reduce((p, c)=>p.add(c["client_os"]), new Set())).sort((a, b)=>a.toUpperCase() > b.toUpperCase() ? 1 : a === b ? 0 : -1);
      console.log(aKeys);

The results

1
[ 'Android', 'iOS', 'Linux', 'OS X', 'unknown', 'Windows' ]

I like the compactness of arrow functions and using sets so there is no logic necessary to figure out whether the value is already there is helpful.
The results are obtained using the webhooks exposed by Mailgun but that is another story.

Share