reduce.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. var reduce = require('../');
  2. var test = require('tape');
  3. test('numeric reduces', function (t) {
  4. t.plan(6);
  5. var xs = [ 1, 2, 3, 4 ];
  6. t.equal(
  7. reduce(xs, function (acc, x) { return acc + x }, 0),
  8. 10
  9. );
  10. t.equal(
  11. reduce(xs, function (acc, x) { return acc + x }, 100),
  12. 110
  13. );
  14. t.equal(
  15. reduce(xs, function (acc, x) { return acc + x }),
  16. 10
  17. );
  18. var ys = cripple([ 1, 2, 3, 4 ]);
  19. t.equal(
  20. reduce(ys, function (acc, x) { return acc + x }, 0),
  21. 10
  22. );
  23. t.equal(
  24. reduce(ys, function (acc, x) { return acc + x }, 100),
  25. 110
  26. );
  27. t.equal(
  28. reduce(ys, function (acc, x) { return acc + x }),
  29. 10
  30. );
  31. });
  32. test('holes', function (t) {
  33. t.plan(4);
  34. var xs = Array(10);
  35. xs[2] = 5; xs[4] = 6; xs[8] = 4;
  36. t.equal(
  37. reduce(xs, function (acc, x) { return acc + x }),
  38. 15
  39. );
  40. t.equal(
  41. reduce(xs, function (acc, x) { return acc + x }, 100),
  42. 115
  43. );
  44. var ys = cripple(Array(10));
  45. ys[2] = 5; ys[4] = 6; ys[8] = 4;
  46. t.equal(
  47. reduce(ys, function (acc, x) { return acc + x }),
  48. 15
  49. );
  50. t.equal(
  51. reduce(ys, function (acc, x) { return acc + x }, 100),
  52. 115
  53. );
  54. });
  55. test('object', function (t) {
  56. t.plan(1);
  57. var obj = { a: 3, b: 4, c: 5 };
  58. var res = reduce(objectKeys(obj), function (acc, key) {
  59. acc[key.toUpperCase()] = obj[key] * 111;
  60. return acc;
  61. }, {});
  62. t.deepEqual(res, { A: 333, B: 444, C: 555 });
  63. });
  64. function cripple (xs) {
  65. xs.reduce = undefined;
  66. return xs;
  67. }
  68. var objectKeys = function (obj) {
  69. var keys = [];
  70. for (var key in obj) {
  71. if (hasOwn.call(obj, key)) keys.push(key);
  72. }
  73. return keys;
  74. };
  75. var hasOwn = Object.prototype.hasOwnProperty;