Search code examples
javascriptunderscore.jschaining

How to use underscore.string's reverse() inside a chain?


I am working with both underscore and underscore.string, and there is a conflict with the function .reverse() since both have a function with the same name.

To avoid conflict, we need to use _.str like this:

_.str.reverse("foobar"); //.reverse("foobar") won't work

However, don't know how to use the underscore.string's .reverse() inside a chain.

I have tried with the following:

var something=_.chain("hello world!")
        .capitalize()
        //_.str
        //_.str()
        //.str
        //.str()
        .reverse()
        .value();

But don't work... Any ideas?


Solution

  • You could use _.mixin to add the _.str.reverse function to the underscore object with another name so it doesn't clash with arrays' reverse:

    _.mixin({strReverse: _.str.reverse});
    var something = _.chain("hello world!").capitalize().strReverse().value();
    console.log(something); // logs "!dlrow olleH"
    

    And a JSFiddle demo, of course.

    Note that after doing that strReverse will also be otherwise accessible in the underscore object:

    console.log(_('hello').strReverse()); // logs "olleh"