From 6f44a8c7785e7e11cc8df1bfa702a8a80019443d Mon Sep 17 00:00:00 2001 From: banned4hax Date: Thu, 16 Apr 2015 18:06:34 -0700 Subject: [PATCH] add function maxVal & minVal The maxVal function will iterate through each of the properties in an object and select for the property that has the greatest numeric value. If there are no properties with in the object that contain a numeric value the generic result ' ["key",-Infinity] ' is returned. The function minVal operates in the same manner except that it selects for the property with the least numeric value and it's default return value is ' ["key", Infinity] '. This offers the user much shorter syntax than than ' _.max(obj,function(property){property;}); ' and also provides the key where the max value resides. I also included it's complimentary minVal function as well. These functions provide a direct cross-over for ruby users looking for ' hash.max_by{|k,v| v} ' & ' hash.min_by{|k,v| v} '. Since these functions are specific to objects, I thought it would be appropriate to put this in object selectors. --- underscore.object.selectors.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/underscore.object.selectors.js b/underscore.object.selectors.js index cd548e6..6d8cc2c 100644 --- a/underscore.object.selectors.js +++ b/underscore.object.selectors.js @@ -109,6 +109,24 @@ keysFromPath: keysFromPath, + //Returns the property with the greatest numeric value in an object along with it's key in an array [key,value]. + maxVal: function(obj){ + + return Object.keys(obj).reduce(function(currentVal, key){ + return obj[key] > currentVal[1] ? [key,obj[key]] : currentVal + }, ["key",-Infinity]); + + }, + + //Returns the property with the least numeric value in an object along with it's key in an array [key,value]. + minVal: function(obj){ + + return Object.keys(obj).reduce(function(currentVal, key){ + return currentVal[1] > obj[key] ? [key,obj[key]] : currentVal + }, ["key",Infinity]); + + }, + pickWhen: function(obj, pred) { var copy = {};