Advertisement
Guest User

Untitled

a guest
Sep 24th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. var reducePolyfill = function(callback) {
  2. var isArray = Array.isArray(this);
  3. var t = Object(this);
  4. var k = Object.keys(this);
  5. var len = isArray ? t.length >>> 0 : k.length >>> 0;
  6. var argLen = arguments.length;
  7. var init;
  8. var i;
  9.  
  10. if (this === null) {
  11. throw new TypeError('Array.prototype.reduce called on null or undefined');
  12. }
  13.  
  14. if (typeof callback !== 'function') {
  15. throw new TypeError(callback + ' is not a function');
  16. }
  17.  
  18. if (len === 0 && argLen === 1) {
  19. throw new TypeError('Reduce of empty array with no initial value');
  20. }
  21.  
  22. if (len === 1 && argLen === 1) {
  23. return this.pop();
  24. }
  25.  
  26. if (len === 0 && argLen === 2) {
  27. return arguments[1];
  28. }
  29.  
  30. if (argLen === 1) {
  31. init = isArray ? t[0] : t[k[0]];
  32. i = 1;
  33. } else {
  34. init = arguments[1];
  35. i = 0;
  36. }
  37.  
  38. for(;i<len;i++) {
  39. init = callback(init, t[k[i]], isArray ? i : k[i]);
  40. }
  41.  
  42. return init;
  43. };
  44.  
  45. Array.prototype.reduce = reducePolyfill;
  46. Object.prototype.reduce = reducePolyfill;
  47.  
  48. console.log({a: 1, b: 2, c: 3}.reduce(function(res, val) {
  49. res += val;
  50. return res;
  51. }, 0));
  52.  
  53. console.log({a: 1, b: 2, c: 3}.reduce(function(res, val, key) {
  54. res += `${key}: ${val}\n`;
  55. return res;
  56. }, ''));
  57.  
  58. console.log([1, 2, 3].reduce(function(res, val) {
  59. res += val;
  60. return res;
  61. }, 0));
  62.  
  63. console.log([1, 2, 3].reduce(function(res, val, key) {
  64. res += `${key}: ${val}\n`;
  65. return res;
  66. }, ''));
  67.  
  68. console.log([1, 2, 3].reduce(function(res, val, key) {
  69. res += val;
  70. return res;
  71. }));
  72.  
  73. console.log([1].reduce(function(res, val, key) {
  74. res += val;
  75. return res;
  76. }));
  77.  
  78. console.log([].reduce(function(res, val, key) {
  79. res += val;
  80. return res;
  81. }, 1));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement