Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaner way of handling Array.prototype.slice.call(arguments)

I'm writing several functions that take different types of parameters. As such, it's much simpler to just do:

var myFunc = function() {
    var args = Array.prototype.slice.call(arguments)
}

...than to try to handle all the different possibilities directly in the parameter field of the function declaration, e.g.:

var myFunc = function(param1, param2, param3) {
    if (param3) {
        // etc.
    }
}

Array.prototype.slice.call(arguments) adds a lot to the code though, and reduces readability. I'm trying to figure out if there's a way to write a helper function that could accomplish the same thing as Array.prototype.slice.call(), but cleaner and easier to read. I was trying something like:

var parseArgs = function() {
    return Array.prototype.slice.call(arguments)
}

var foo = function() {
    console.log(parseArgs(arguments))
}

foo('one', 'two', 'three')
// [Arguments, ['one', 'two', 'three']]

But obviously that doesn't work.

like image 840
brandonscript Avatar asked Dec 15 '22 09:12

brandonscript


2 Answers

If you don't want to write Array.prototype.slice.call(args) everytime you can do:

var slice = Function.call.bind(Array.prototype.slice);

And then you can use it anywhere like:

function fn(){
    var arr = slice(arguments);
}
like image 115
MinusFour Avatar answered Dec 17 '22 02:12

MinusFour


A few shorthands for converting array-like objects to actual arrays in JS:

Alias Array.prototype.slice:

(function (slice) {
  ...your code...
  function someFunction() {
    var args = slice.call(arguments);
    ...
  }
  ...
}(Array.prototype.slice));

Use [].slice:

function someFunction() {
  var args = [].slice.call(arguments);
}

Create your own slice (you tried this but had an error in the arguments):

function slice(arr) {
  return Array.prototype.slice.call(arr);
}
function someFunction() {
  var args = slice(arguments);
}

Use the modern Array.from (be sure to polyfill for backwards compatibility):

function someFunction() {
  var args = Array.from(arguments);
}

If you're in an environment where you can safely use the spread operator, then there is no need for any call to slice:

function someFunction() {
  var args = [...arguments];
}
like image 20
zzzzBov Avatar answered Dec 17 '22 02:12

zzzzBov