I am trying to mock the times function from the JavaScript library Underscore.js.
This function accepts two syntaxes :
_.times(3, function(n) {
    console.log("hello " + n);
});
and
_(3).times(function(n) {
    console.log("hello " + n);
});
So far I succeeded to mock the first one by creating an _ object like this :
var _ = {
    times: function(reps, iteratee) {
        // a loop
    }
};
And the second syntax by creating an _ function which returns an object :
function _(n) {
    return {
        times: function(iteratee) {
            // a loop
        }
    };
}
But I can't use these 2 methods together. I need to find a way that will allow both syntaxes.
Do you have any idea how I could use the _ character as an object as well as a function ?
You should be able to combine two syntaxes like this:
var _ = (function() {
    var times = function(n, iteratee) {
        // a loop
    };
    function _(n) {
        return {times: function(iteratee) {
            return times(n, iteratee);
        }}; // or shorter: {times: times.bind(null, n)}
    }
    _.times = times;
    return _;
})();
Here you benefit from the fact that functions are also objects and hence can have properties.
Functions are objects in Javascript, so you could just do something like this:
var _ = function(a,b) { /* ... */ };
_.times = _;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With