Prepend argument to arguments then apply

apply, arguments, call, javascript

Solution

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?

Problem

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] ```

Original source

Related problems