Hesan Aminiloo
Hesan Aminiloo

Reputation: 428

How Babel transpiles the rest/spread operator

I was wondering how Babel transpiles this code?

const test = ({ val1, val2, ...rest }) => val1.toLowerCase();

test({
  val1: 'Test',
  val2: 'other',
  o1: 'other',
  o2: 'Another'
});

It's a dummy function that gets an object as the argument and returns the val1 toLowerCase. So nothing magical.

Upvotes: 1

Views: 959

Answers (1)

Hesan Aminiloo
Hesan Aminiloo

Reputation: 428

It's not that complicated. It will create an array of excluded properties like: ['val1', 'val2'] and pass the whole object and exclude array to a function:

var test = function test(_ref) {
var val1 = _ref.val1,
  val2 = _ref.val2,
  rest = _objectWithoutProperties(_ref, ["val1", "val2"]);
  return val1.toLowerCase();
};

The implementation of the _objectWithoutProperties is like this:

function _objectWithoutProperties(source, excluded) {
  if (source == null) return {};
  // This does the trick
  var target = _objectWithoutPropertiesLoose(source, excluded);

  var key, i;
  // If the object keys were Symbols it will append them too. 
  // If we don't have any symbols this was unnecessary
  if (Object.getOwnPropertySymbols) {
    var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
    for (i = 0; i < sourceSymbolKeys.length; i++) {
      key = sourceSymbolKeys[i];
      if (excluded.indexOf(key) >= 0) continue;
      if (
        !Object.prototype.propertyIsEnumerable.call(source, key)
      ) continue;
      target[key] = source[key];
    }
  }
  return target;
}

And finally _objectWithoutPropertiesLoose implementation is like this:

function _objectWithoutPropertiesLoose(source, excluded) {
  // if the source object was null so there's nothing to return
  if (source == null) return {};

  // initialize an empty object to assign values to it later 
  var target = {};

  // get an array of keys from the source object and loop through it
  var sourceKeys = Object.keys(source);

  var key, i;
  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];

    // THIS IS WHERE IT HAPPENS: if the current key was present on the excluded array, so skip this iteration
    if (excluded.indexOf(key) >= 0) continue;

    // add the value with that key into the target object
    target[key] = source[key];
  }

  // return the target object
  return target;
}

Upvotes: 3

Related Questions