LoginSignup
20
19

More than 5 years have passed since last update.

if文をきれいに書く方法

Last updated at Posted at 2013-06-13

kotaziです。
- kotazi.com

速度記号を返す関数(getDaCapo)


よくあるif文で書く。

dacapo.js

var getDaCapo = function(tempo) {
  var dacapo = null;

  if(tempo < 30) {
    //error
  }else if(tempo >= 30 && tempo < 60) {
    dacapo = "largo";
  }else if(tempo >= 60 && tempo < 66){
    dacapo = "larghetto";
  }else if(tempo >= 66 && tempo < 76){
    dacapo = "adagio";
  }else if(tempo >= 76 && tempo < 108){
    dacapo = "andante";
  }else if(tempo >= 108 && tempo < 120){
    dacapo = "moderato";
  }else if(tempo >= 120 && tempo < 168){
    dacapo = "allegro";
  }else if(tempo >= 168 && tempo < 200){
    dacapo = "presto";
  }else if(tempo >= 200 && tempo < 300){
    dacapo = "prestissimo";
  }else{
    //error
  }
};

上記の場合、条件文が直感的に分かりにくい。

そのため、以下のように
return値で値を返すようにすると、
パッと見て何が書いてあるかを理解しやすくなる。

dacapo.js


var getDaCapo = function(tempo) {
  var dacapo = null;

  if(tempo < 30) {
    //error
    return;
  }
  if(tempo < 60) {
    dacapo = "largo";
    return dacapo;
  }
  if(tempo<66){
    dacapo = "larghetto";
    return dacapo;
  }
  if(tempo<76){
    dacapo = "adagio";
    return dacapo;
  }
  if(tempo<108){
    dacapo = "andante";
    return dacapo;
  }
  if(tempo<120){
    dacapo = "moderato";
    return dacapo;
  }
  if(tempo<168){
    dacapo = "allegro";
    return dacapo;
  }
  if(tempo<200){
    dacapo = "presto";
    return dacapo;
  }
  if(tempo<300){
    dacapo = "prestissimo";
    return dacapo;
  }
  if(tempo>300){
    //eroor
    return dacapo;
  }

};
20
19
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
19