jashkenas / underscore

JavaScript's utility _ belt
https://underscorejs.org
MIT License
27.3k stars 5.53k forks source link

_.replace collection function? #955

Closed jbenet closed 11 years ago

jbenet commented 11 years ago

Hello folks,

Wondering if there is interest in something like this:

_.replace = function(obj, filter, replace) {
  return _.map(obj, function(value, index, list) {
    if (_.isFunction(filter) ? filter(value, index, list) : filter == value)
      return _.isFunction(replace) ? replace(value, index) : replace;
    return value;
  });
};

I often find myself mapping a collection just to replace an element. I much prefer _.replace(words, 'foo', 'bar') or even:

_.replace(words, function(word) { 
  return badWords[word] || word == user.password;
}, '****')

than these:

_.map(words, function(word) {
  return (word == 'foo') 'bar' : word;
});

_.map(words, function(word) {
  if (badWords[word] || word == user.password)
    return '****';
  return word;
});

If this is relevant to your interests, I'm happy to implement + send a PR.

Cheers, Juan

jashkenas commented 11 years ago

Neat idea -- but I think that your examples of map are both clearer and more flexible. Feel free to add replace via mixin in your copy.