2017-01-20 9 views
0

ロジックを複製する2つの関数がありますが、私は自分のコードをリファクタリングしたいと思います。型として渡される値は、「day」または「night」です。機能は以下のとおりです。関数名に変数を使用する

function doBooking(type, rate, nights) { 
    if (type=="day") { 
    reservation.day(rate, nights, function(err, data) { 
     do (a) 
     do (b) 
     do (c) 
    }); 
    } else { 
    reservation.night(rate, nights, function(err, data) { 
     do (a) 
     do (b) 
     do (c) 
    }); 
    } 
}); 

私は賢いことと、これは以下のようなものにするために改善したいと思いますが、それはうまく動作しませんでした...

function doBooking(type, rate, nights) { 
    ["reservation."+type](rate, nights, function(err, data) { 
    do (a) 
    do (b) 
    do (c) 
    }); 
}); 
+1

あなたはほとんどそこにあります。 1つの小さな修正とあなたの機能が動作します。 ''予約を変更するだけです。 + type] '予約' {type} ' –

答えて

0

このような何か試してみてください:

function doBooking(type, rate, nights) { 
    var _type = (type === "day") ? "day" : "night"; 
    reservation[_type](rate, nights, function(err, data) { 
    do (a) 
    do (b) 
    do (c) 
    }); 
}); 
0

同じビジネスロジックを共有している場合、昼夜の別々の機能を使用するのはどうしてですか?あなたは時間の別の議論を追加できませんでしたか?

function doBooking(type, rate, nights) { 
    reservation.make(type, rate, nights, function(err, data) { 
     // (a), (b), & (c) happen inside the reservation handler 
     // If you do anything unique to day or night, do it here in the callback of the generic handler 
    }); 
} 

これ以外にも、ここで機能を分けることができるはるかにクリーンな方法があります。あなたが知られているタイプを扱うことができますので、予約を処理するために定義されたクラスを開始します。

function Reservation (type, customer) { 
    this.type = type 
    this.customer = customer 
    this.rate 
    this.nights = [] 
    this.isBooked 
    this.make = function(callback) { 
     longRunningBookingOperation(this, function(err, data) { 
      this.isBooked = data.result === "success" && !err 
      callback(err, data) 
     }) 
    } 
} 

そして、それを使用する:

const customer = Customer({firstname: "Tom", lastname: "Jones", id: 2392015572-1827}) 
var reservation = Reservation(ReservationTypeDay, customer) 
reservation.make(err, data) { 
    // handle the result 
}) 
+0

' function(err、data){} //コールバックのように見えます。 多分、夜の予約で、彼は確認メールを送っています。そして、約束が解決するまで待つことになっています。だから私は、タスクを実行するために異なる機能を持っていることが理にかなっていると思う。 – slackmart

+0

ああ、しかし、_ "彼らのロジックを複製する2つの機能を持っている" _は偽の記述です。ビジネスロジックが異なっていて、共通コードのみを共有する場合は、大規模なリファクタリングが順番に行われ、おそらくビジネス関数自体が値ではなくパラメータとして渡されます。 – brandonscript

+0

ああ、それは不明です。おそらく「*私はそのロジックを複製する2つの関数を持っている」*コールバック関数(エラー、データ){ do(a) do(b) do(c) } – slackmart

関連する問題