Skip to content

switch generates unneeded breaks #5344

Closed
@edemaine

Description

@edemaine

This is a feature request that surfaces as a bug when trying to use eslint with standard rules, specifically the no-unreachable rule.

Input Code

convertToBoolean = (string) ->
  switch string
    when 'yes', 'Yes'
      if string.startsWith 'Y'
        'True'
      else
        'true'
    when 'no'
      'false'
    else
      null

try link

Expected Behavior

var convertToBoolean;

convertToBoolean = function(string) {
  switch (string) {
    case 'yes':
    case 'Yes':
      if (string.startsWith('Y')) {
        return 'True';
      } else {
        return 'true';
      }
    case 'no':
      return 'false';
    default:
      return null;
  }
};

Current Behavior

Currently, CoffeeScript generates dead/inaccessible break in the first case (because of the if expression) but it's smart enough not to in the second case.

var convertToBoolean;

convertToBoolean = function(string) {
  switch (string) {
    case 'yes':
    case 'Yes':
      if (string.startsWith('Y')) {
        return 'True';
      } else {
        return 'true';
      }
      break;
    case 'no':
      return 'false';
    default:
      return null;
  }
};

Possible Solution

Ideally, the existing mechanism for not generating break lines in switch statements can apply to complex implicit return expressions (such as if expressions), not just simple expressions.

Context

One could argue that the extra break statements are fine to leave in. Unfortunately, this 2016 eslint issue disagrees with this argument, so there's no easy way to allow these break statements in eslint without allowing all dead code (i.e. disabling the no-unreachable).

Environment

Live demo on try website

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions