Sunday, November 12, 2017

Javascript Array intersection

Simple Javascript Array intersection

Example Fiddle

function intersection (...args) {
  if (args.length < 2) return []
  
  const source = args.shift()
  const src = Array.isArray(source) ? source : []
  
  return src.reduce((intersections, value, index, list) => {    
    const intersects = args.reduce((state, array) => {
        return Array.isArray(array) ?
          state && array.indexOf(value) !== -1 :
          state
    }, true)
    
    if (intersects && intersections.indexOf(value) === -1) {
     intersections.push(value)
    }
    
    return intersections
  }, [])
}

Saturday, November 11, 2017

Javascript Promise Reduction

Simple function to perform a reduce on an iterable of Promise/Non-Promise objects.

function promiseReduce (iterable, reducer, initialValue) {
  return iterable.reduce((previousPromise, currentPromise, count) => {
    return Promise.resolve(previousPromise).then(result => {
      return Promise.resolve(currentPromise).then(current => {
        return reducer(result, current, count)
      })
    })
  }, Promise.resolve(initialValue))
}
See fiddle
Or you can use Bluebird.js