user2924127
user2924127

Reputation: 6240

Spread operator alternative

I have the following code I received:

function sortByProp(...props) {
  const callback = props.pop();
  return function(a, b) {
    const v1 = retrieve(props, a);
    const v2 = retrieve(props, b);
    return callback(v1, v2);
  } 
}

It works great in most browsers, but not in opera. I get the following error:

function sortByProp(...props) {
                    ^^^
SyntaxError: Unexpected token ...

I visited https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator to see if there is an alternative to see if there is a polyfill for this, but I can't find one.

I call this function using these two:

.sort(sortByProp('key', 'k', a))
          .sort(sortByProp('key', 'n', b));

How can I make it so this will work in all browsers?

Upvotes: 2

Views: 3658

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

You can't polyfill syntax. It just doesn't work. Syntax checking happens before any logic from a polyfill can occur. What you can do is use compilers like Babel to convert your ES2015 code down to ES5. Or you can rewrite your function to use arguments:

function sortByProp() {
  var props = [].slice.call(arguments);
  const callback = props.pop();
  return function(a, b) {
    const v1 = retrieve(props, a);
    const v2 = retrieve(props, b);
    return callback(v1, v2);
  } 
}

Upvotes: 6

Related Questions