arrays.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. function empty(array){
  2. return !!!array.length
  3. }
  4. function throwIfEmpty (array, method){
  5. if(!array.length){
  6. var err = new Error('arrays.' + method + ' cannot take an empty array')
  7. err.type = 'EmptyArray'
  8. throw err
  9. }
  10. }
  11. function strictInit (array){
  12. throwIfEmpty(array)
  13. return [].slice.call(array, 0, array.length - 1)
  14. }
  15. function strictTail(array){
  16. throwIfEmpty(array)
  17. return [].slice.call(array, 1, array.length )
  18. }
  19. function strictLast(array){
  20. throwIfEmpty(array)
  21. return array[array.length -1]
  22. }
  23. function strictHead(array){
  24. throwIfEmpty(array)
  25. return array[0]
  26. }
  27. function init (array){
  28. return empty(array) ? [] : [].slice.call(array, 0, array.length - 1)
  29. }
  30. function tail(array){
  31. return empty(array) ? [] : [].slice.call(array, 1, array.length )
  32. }
  33. function last(array){
  34. return empty(array) ? null : array[array.length - 1]
  35. }
  36. function head(array){
  37. return empty(array) ? null : array[0]
  38. }
  39. function flatten (nested) {
  40. var a = []
  41. function denest (item) {
  42. if(Array.isArray(item))
  43. item.forEach(denest)
  44. else a.push(item)
  45. }
  46. denest(nested)
  47. return a
  48. }
  49. module.exports = {
  50. throwIfEmpty: throwIfEmpty,
  51. init: init,
  52. tail: tail,
  53. last: last,
  54. head: head,
  55. strictInit: strictInit,
  56. strictTail: strictTail,
  57. strictLast: strictLast,
  58. strictHead: strictHead,
  59. empty: empty,
  60. flatten: flatten,
  61. union: union
  62. }
  63. function union (a, b) {
  64. var c = []
  65. function add (item) {
  66. if(!~c.indexOf(item))
  67. c.push(item)
  68. }
  69. if(a) a.forEach(add)
  70. if(b) b.forEach(add)
  71. return c
  72. }