Skip to content

Instantly share code, notes, and snippets.

@johnhunter
Created October 27, 2010 19:48
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save johnhunter/649811 to your computer and use it in GitHub Desktop.
Save johnhunter/649811 to your computer and use it in GitHub Desktop.
jQuery.reduce - a jQuery plugin for functional programming
/*
jQuery.reduce - a jQuery plugin for functional programming
@author John Hunter
created 2010-09-17
use: $.reduce(arr, fnReduce, valueInitial);
fnReduce is called with arguments: [valueInitial, value, i, arr]
reduce will never be jQuery core - its not prototype :p (http://dev.jquery.com/ticket/1886)
*/
(function ($) {
$.reduce = function(arr, fnReduce, valueInitial) {
if (Array.prototype.reduce) {
return Array.prototype.reduce.call(arr, fnReduce, valueInitial);
}
$.each(arr, function(i, value) {
valueInitial = fnReduce.call(null, valueInitial, value, i, arr);
});
return valueInitial;
};
})(jQuery);
@rmkane
Copy link

rmkane commented Feb 22, 2016

👍

(function($) {
  $.reduce = function(arr, fnReduce, valueInitial) {
    if (Array.prototype.reduce) {
      return Array.prototype.reduce.call(arr, fnReduce, valueInitial);
    }
    $.each(arr, function(i, value) {
      valueInitial = fnReduce.call(null, valueInitial, value, i, arr);
    });
    return valueInitial;
  };
  $.fn.reduce = function(fnReduce, valueInitial) {
    return $.reduce(this, fnReduce, valueInitial);
  };
})(jQuery);

@zaus
Copy link

zaus commented Sep 21, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment