Function expressions to arrow functions

JavaScript pattern

Converts function expressions to ES6 arrow functions, including eliminating the return statement where possible.


Apply with the Grit CLI
grit apply es6_arrow_functions

Transform function expressions

BEFORE
var increment = function (i) {
  return i + 1;
};

var remember = function (me) {
  this.you = me;
};

var sumToValue = function (x, y) {
  function Value(v) {
    this.value = v;
  }
  return new Value(x + y);
};

var times = (x, y) => {
  return x * y;
};
AFTER
var increment = (i) => {
  return i + 1;
};

var remember = function (me) {
  this.you = me;
};

var sumToValue = (x, y) => {
  function Value(v) {
    this.value = v;
  }
  return new Value(x + y);
};

var times = (x, y) => x * y;

Wraps objects correctly

An arrow function can return an object directly, but it must be wrapped in parentheses.

BEFORE
const dummyAnswer = (type) => {
  return {
    dataset: function (name, query) {
      return 1;
    },
  };
};
AFTER
const dummyAnswer = (type) => ({
  dataset: (name, query) => {
    return 1;
  },
});