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;
  },
});

Handles async functions correctly

See this issue.

Before:

BEFORE
const a = {
  set: async function () {
    return await Promise.resolve(1);
  },
};

After:

AFTER
const a = {
  set: async () => {
    return await Promise.resolve(1);
  },
};

Handles async return values

When removing an unnecessary return statement, we still need to consider if the function is async.

BEFORE
const a = async () => {
  return await Promise.resolve(1);
};

After:

AFTER
const a = async () => await Promise.resolve(1);