QubitProducts / slapdash

A lightweight JavaScript utility belt with native method override protection
http://npmjs.org/packages/slapdash
MIT License
3 stars 1 forks source link

Add _.toArray method #53

Open sgrowek opened 7 years ago

sgrowek commented 7 years ago

When writing experiences which use native browser methods instead of jQuery, it's very helpful to convert the NodeLists etc. to arrays so that you can then make use of Array.prototype.map and Array.prototype.filter for example. This is preferable over using the slapdash _.map and _.filter as they chain much more readably (and they are available in all browsers supported by experiences these days).

Therefore it would be nice to have a _.toArray(arrayLike) method in slapdash which converts array-like objects with a length property and indexes into a plain array. This method could fall back to Array.from when it's available.

Before:

const serviceInputs = _.map(document.querySelectorAll('.list-services'),
  el => el.querySelector('input[type=hidden]'))

_.map(_.filter(serviceInputs, input => input), input => input.name)

After:

_.toArray(document.querySelectorAll('.list-services'))
  .map(el => el.querySelector('input[type=hidden]'))
  .filter(input => input)
  .map(input => input.name)

An alternative solution to the chaining/readability problem might be to add something like lodash's flow: https://lodash.com/docs/#flow