sindresorhus/eslint-plugin-unicorn

Rule proposal: Consistent function scoping #230

futpib posted onGitHub

A function definition should be placed as close to the top level scope as possible without breaking it's captured values.

Fail

export function create(context) {
  // does not capture anything from the scope, can be moved to the outer scope
  function isSpecial(node) {
    return node.type === 'Special';
  }

  return isSpecial;
}

Pass

function isSpecial(node) {
  return node.type === 'Special';
}

export function create(context) {
  return isSpecial;
}
export function create(context) {
  function isSpecial(node) {
    return node.type === 'Special' && context.isSpecial(node);
  }

  return isSpecial;
}

Sounds good. I often have to manually comment about this in PR reviews.

posted by sindresorhus about 6 years ago

Slightly off-topic, but I would like the inverse for variables. That they are placed in the most inner scope as possible. What do you think?

posted by sindresorhus about 6 years ago

This might actually be perfectly on-topic, because of the interaction between the two rules.

In this example, should context be moved in, or should isSpecial be moved out? (I have no idea yet)

const context = undefined;

export function create() {
  function isSpecial(node) {
    return node.type === 'Special' && context.isSpecial(node);
  }

  return isSpecial;
}
posted by futpib about 6 years ago

On a second thought, moving variables in may be a bad idea because it may negatively affect performance.

posted by futpib about 6 years ago

Yeah, let's keep this focused on only functions for now. And yes it should be moved out.

posted by sindresorhus about 6 years ago

@issuehunt has funded $80.00 to this issue.


posted by IssueHuntBot almost 6 years ago

I have a prototype for this working; hope to have a PR out in the next couple days.

posted by MrHen almost 6 years ago

Alternative rule names:

  • function-scoping
  • function-lifting
  • function-hoisting
posted by golopot over 5 years ago

@sindresorhus has rewarded $72.00 to @mrhen. See it on IssueHunt

  • :moneybag: Total deposit: $80.00
  • :tada: Repository reward(0%): $0.00
  • :wrench: Service fee(10%): $8.00
posted by issuehunt-app[bot] over 5 years ago

Fund this Issue

$80.00
Rewarded

Rewarded pull request

Recent activities

mrhen was rewarded by sindresorhus for sindresorhus/eslint-plugin-unicorn# 230
over 5 years ago
mrhen submitted an output to  sindresorhus/ eslint-plugin-unicorn# 230
almost 6 years ago