ajax333221
ajax333221

Reputation: 11764

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?

Upvotes: 0

Views: 2231

Answers (2)

Felix Loether
Felix Loether

Reputation: 6188

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"

Upvotes: 3

Wayne
Wayne

Reputation: 60414

The object returned by capitalize() must support the next method in the chain, but it does not. It's a mistake to think you can somehow refer to another object's method by name inside the chain. It simply doesn't work that way. In short, you'll need to solve this another way.

Upvotes: 0

Related Questions