All files collections.js

84.85% Statements 28/33
71.43% Branches 10/14
92.86% Functions 13/14
89.66% Lines 26/29
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 623x 3x           10x 10x 10x     10x       2x 2x 2x 2x 2x   6x   2x         1x       11x 10x 9x   1x   5x 5x           1x         2x 8x 3x 5x 5x            
import { isNumber, isIndexed, truthy, existy } from './predicates';
import { fail } from './util';
import { toArray } from 'lodash';
 
// Function that takes an array or string and returns an element at the
// requested index.
function nth(value, idx) {
  Iif (!isNumber(idx)) fail('Expecting index to be a number');
  Iif (!isIndexed(value)) fail('Expecting array or string');
  Iif ((idx < 0) || (idx > value.length - 1)) {
    fail('Index is out of bounds');
  }
  return value[idx];
}
 
// Utility functions for accessing variables in indexed data types
export function first(val)  { return nth(val, 0) };
export function second(val) { return nth(val, 1) };
export function third(val)  { return nth(val, 2) };
export function fourth(val) { return nth(val, 3) };
export function fifth(val)  { return nth(val, 4) };
 
export function rest(array) {
  const [first, ...rest] = array;
  return rest;
}
export function tail(array) { return rest(array) };
 
export function butLast(coll) {
  return toArray(coll).slice(0, -1);
}
 
// Utility for creating new collections
export function cat(head, ...rest) {
  if (existy(head))
    return head.concat.apply(head, rest);
  else
    return [];
}
export function construct(head, ...tail) {
  return cat([head], ...tail);
}
 
// application function that calls a function for every element of the
// collection and then concats the mapped results together.
export function mapcat(fun, collection) {
  return cat.apply(null, collection.map(fun));
}
 
// Sorting collections
export function comparator(pred) {
  return (x, y) => {
    if (truthy(pred(x, y)))
      return -1;
    else Eif (truthy(pred(y, x)))
      return 1;
    else
      return 0;
  }
}