All files array.js

76.67% Statements 23/30
71.43% Branches 15/21
46.15% Functions 6/13
87.5% Lines 21/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86      19x   6x   1x 2x 1x   1x   10x 10x 10x                 1x 4x 1x   3x 3x   30x 30x 30x                                 1x                 1x                 1x         1x                        
import { obj } from './object'
 
// ======== Array
const isArray = a => a && Array.isArray(a)
 
const get = (a, index, defaultValue) => (isArray(a) && typeof a[index] !== 'undefined' ? a[index] : defaultValue)
 
const objByKey = (a, key) => {
  if (!isArray(a)) {
    return {}
  }
  return a.reduce(
    (agg, t) => {
      const okey = obj.get(t, key, 'default')
      const oval = obj.get(agg, okey, [])
      return {
        ...agg,
        [okey]: [...oval, t],
      }
    },
    {}
  )
}
 
const objByPages = (a, rows = 0) => {
  if (!isArray(a)) {
    return { 1: [] }
  }
  const inRows = (!Number.isInteger(rows) || rows === 0 ? 10 : rows)
  return a.reduce(
    (agg, t, i) => {
      const okey = Math.trunc(i / inRows) + 1
      const oval = obj.get(agg, okey, [])
      return {
        ...agg,
        [okey]: [...oval, t],
      }
    },
    {}
  )
}
 
/**
 * Checks whenever 2 arrays have intersection
 *
 * @param {Array} a
 * @param {Array} b
 *
 * @return {Boolean}
 */
export const hasintersect = (a, b) => a.reduce((r, x) => r || b.includes(x), false)
 
/**
 * Returns unique values from 2 arrays
 * @param {Array} a
 * @param {Array} b
 *
 * @return {Array}
 */
export const unique = (a, b) => b.reduce(
  (r, x) => (r.includes(x) ? r : [...r, x]),
  a.reduce((r, x) => (r.includes(x) ? r : [...r, x]), []),
)
 
/**
 *
 * @param a
 */
export const keyUnique = (a, key) => a.reduce(
  (r, x) => [...unique(r, obj.get(x, key, []))],
  [],
)
 
export const arr = {
  isArray,
  get,
  objByKey,
  objByPages,
  hasintersect,
  unique,
  keyUnique,
}
 
 
export default arr