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]
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?
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);
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