max-lines-per-function

Enforce a maximum number of lines in a function

A function that doesn't fit on the screen is hard to read in one go, and it usually does several jobs that could each have a name. This rule reports any function with more lines than the maximum, which is 50 by default.

The count runs from the line where the function starts to the line where it ends.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"max-lines-per-function" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"max-lines-per-function" = ["error", {
  max = 50,
  skipBlankLines = false,
  skipComments = false,
  IIFEs = false,
}]

Examples#

With a maximum of 5, this 7-line function is reported:

example.jswith 51 problem
function checkout(cart) {
  let total = 0;
  for (const item of cart.items) {
    total += item.price * item.count;
  }
  charge(cart.user, total);
}
example.jswith 5No problems
function totalOf(cart) {
  let total = 0;
  for (const item of cart.items) total += item.price * item.count;
  return total;
}

function checkout(cart) {
  charge(cart.user, totalOf(cart));
}

Options#

bunfig.toml
[lint.rules]
max-lines-per-function = ["error", {
  max = 80,
  skipBlankLines = true,
  skipComments = true,
}]
OptionDefaultWhat it does
max50The number of lines a function can have.
skipBlankLinesfalseDon't count lines that are empty or only have whitespace.
skipCommentsfalseDon't count lines that only have a comment.
IIFEsfalseAlso check a function that's called where it's written, like (function () { ... })().

A number alone is short for { "max": number }.

This function has 5 lines, so a maximum of 3 reports it:

example.jswith 31 problem
function greet(user) {
  // Fall back to the login name.

  return `Hello, ${user.name ?? user.login}`;
}

Without the comment and the blank line it has 3:

example.jswith { "max": 3, "skipBlankLines": true, "skipComments": true }No problems
function greet(user) {
  // Fall back to the login name.

  return `Hello, ${user.name ?? user.login}`;
}

A function that's called where it's written is skipped by default. This passes with a maximum of 2:

example.jswith 2No problems
(function () {
  setup();
  start();
})();

With IIFEs it's reported:

example.jswith { "max": 2, "IIFEs": true }1 problem
(function () {
  setup();
  start();
})();