Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend argument to arguments then apply

I have a function, message that takes one param to define the type of message and then it joins any other arguments to form the message, purely a nicety.

It looks like this:

function message(type) {
    var msg = _.rest(arguments).join(" ");

    // Really the type will be used to set the class on a div
    // But I'm just using console.log to keep it simple for now.
    console.log(type + ": " + msg);
}

I want to provide helper functions, error, warning, info, which simply call message with the right type. I'm just unsure on the best way to go about this. I cant think of two ways but I'm not sure if I'm going about it correctly or that perhaps I'm overcomplicating things.

The first way seems a bit redundant, make a new array containing the first arg and the arguments then flatten it.

message.apply(this, _.flatten(["error", arguments]));

The second way feels a bit... messy?

Array.prototype.unshift.call(arguments, "error");
message.apply(this, arguments);

Though from my experiement:

(function() {
    Array.prototype.unshift.call(arguments, 0);
    console,log(arguments);
})(1, 2, 3);

I get the following output:

[0, 1, 2, 3, undefined, undefined, undefined, ..., undefined]
like image 477
Lerp Avatar asked Apr 24 '14 10:04

Lerp


2 Answers

var args = Array.prototype.slice.call(arguments); // Make real array from arguments
args.unshift("error");
message.apply(this, args);

See How can I convert the "arguments" object to an array in JavaScript?

like image 199
Barmar Avatar answered Sep 28 '22 01:09

Barmar


In ES5 this might be slightly more efficient than converting to a real array first and then unshift:

var args = Array.prototype.concat.apply(["error"], arguments);
message.apply(this, args);

EDIT: Better to avoid flattening input arrays:

var args = ["error"];
args.push.apply(args, arguments);
message.apply(this, args);
like image 25
jjrv Avatar answered Sep 28 '22 02:09

jjrv