esamattis / underscore.string

String manipulation helpers for javascript
http://esamattis.github.com/underscore.string/
3.37k stars 375 forks source link

Allow conflicting functions via type detection #62

Open ryanbutterfield opened 13 years ago

ryanbutterfield commented 13 years ago

Maybe you could suggest (or provide a helper function) that conflicting functions could override the underscore equivalents via wrappers that detect whether the argument passed is a String or other Object.

This would avoid potential bugs when someone uses the wrong function for the wrong type.

This is what I have done in my project and it seems to work well:

_.mixin(_.str.exports());

// functions that conflict with _ and _.prototype
_.mixin(_.reduce(['include', 'contains'], function(memo, f) {
  var str = _.str[f], und = _[f];
  memo[f] = function(obj) {
    return (_.isString(obj) ? str : und).apply(this, arguments);
  };
  return memo;
}, {}));

// functions that just conflict with _.prototype
_.each(['reverse'], function(f) {
  var wstr, str = _.str[f], wund = _.prototype[f]; 
  _.mixin({__tmp: str}); // get access to addToWrapper
  wstr = _.prototype.__tmp;
  _[f] = str;
  _.prototype[f] = function() {
    return (_.isString(this._wrapped) ? wstr : wund).apply(this, arguments);
  };
});

Thanks for a great library!

edtsech commented 13 years ago

I think it's the good idea. Could you create the pull request? I think, it can be a part of exports function.

edtsech commented 12 years ago

Any thoughts guys? @epeli, @rwz, @kossnocorp

machineghost commented 11 years ago

Just a quick comment from the peanut gallery: I've been combining Underscore's contains with Underscore.string's (using type detection) for months now, and it works great! I was actually going to submit a ticket for it when I saw this one; congrats to @ryanbutterfield for beating me to it ;-)

By the way, for what it's worth my implementation of the combined contains is slightly different; if anyone is curious:

var originalContains = _.contains;
var combinedContains = function(initialArg) {
    var contains = typeof initialArg == 'string' ? _.string.contains : originalContains;
    return contains.apply(this, arguments);
};
_.mixin({contains: combinedContains, include: combinedContains});
machineghost commented 10 years ago

It's more than a year later, but this is still a good idea. There should be no need for everyone to roll their own "contains" when Underscore string could very easily merge the base version together. Please consider it!