From 9b1da9b2581ecfe549abeb443f81e4feca76bbbc Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Thu, 29 Oct 2009 11:03:53 -0400 Subject: [PATCH] optimized keys, values, and pluck --- index.html | 4 ++-- underscore.js | 16 ++++------------ 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/index.html b/index.html index 33716be85..883780995 100644 --- a/index.html +++ b/index.html @@ -298,8 +298,8 @@ _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');

pluck_.pluck(list, propertyName)
- An optimized version of what is perhaps the most common use-case for - map: returning a list of property values. + An convenient version of what is perhaps the most common use-case for + map: extracting a list of property values.

 var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
diff --git a/underscore.js b/underscore.js
index 7a3d43646..444ee010f 100644
--- a/underscore.js
+++ b/underscore.js
@@ -149,11 +149,9 @@
     });
   };
   
-  // Optimized version of a common use case of map: fetching a property.
+  // Convenience version of a common use case of map: fetching a property.
   _.pluck = function(obj, key) {
-    var results = [];
-    _.each(obj, function(value){ results.push(value[key]); });
-    return results;
+    return _.map(obj, function(value){ return value[key]; });
   };
   
   // Return the maximum item or (item-based computation).
@@ -357,18 +355,12 @@
   
   // Retrieve the names of an object's properties.
   _.keys = function(obj) {
-    return _.reduce(obj, [], function(memo, value, key) { 
-      memo.push(key);
-      return memo;
-    });
+    return _.map(obj, function(value, key){ return key; });
   };
   
   // Retrieve the values of an object's properties.
   _.values = function(obj) {
-    return _.reduce(obj, [], function(memo, value) { 
-      memo.push(value); 
-      return memo; 
-    });
+    return _.map(obj, identity);
   };
   
   // Extend a given object with all of the properties in a source object.