2013-08-07 49 views
0

Fellow Stackers,JavaScript循環,從總數中減去,直到不再有任何東西

我不知道如何讓我的「bundler」函數循環。我希望能夠通過不同的數量並根據數量決定哪個箱子/組合是最佳匹配。更大的盒子有更大的折扣。我試圖通過減去捆綁包中有多少物品,以及將多少物品放入箱子並循環通過它來完成此操作,但我不確定我的語法有什麼問題。對於任何反饋,我們都表示感謝。

也就是說,1件商品將進入1盒,價格爲250美元 也就是說。 22個項目,將進入兩個10個框和兩個1個框。 也就是說。 39個項目,將進入三個10個盒子,一個5個盒子和四個1個盒子

function product(sku, name, quantity, cost) { 
     this.sku = sku; 
     this.name = name; 
     this.quantity = quantity; 
     this.cost = cost; 
    } 

    function bundler(quantity) { 
     var remainder = quantity; 
     while (remainder > 0) { 
     var bundle = []; 
     switch (true) { 
     case (quantity >= 10): 
      box_10 = new product(3333,"Box of 10",1,1500); 
      bundle.push(box_10); 
      remainder = quantity - 10; 
      return bundle; 
     case (remainder >= 5 && remainder <= 9): 
      box_5 = new product(2222,"Box of 5",1,1000); 
      bundle.push(box_5); 
      remainder = remainder - 5; 
      return bundle; 
     case (remainder <=4 && remainder > 0): 
      bundle = new product(1111,"Box of 1",remainder,250); 
      remainder = remainder - remainder; 
      return bundle; 
     } 
     } 
    } 

    var order = bundler(19); 
+0

爲什麼不直接使用模師,並Math.floor?將框的類型放入一個整數數組中,並循環其元素。如果Math.floor值大於零,請使用該大小的許多框。如果餘數(通過modulo)大於零,請嘗試下一個框大小。將結果存儲到新的整數數組中。 – cabbagery

+0

@cabbagery,我不知道該怎麼做。也許你可以發表一個例子? –

回答

1

試試這個;

function product(sku, name, quantity, cost) { 
    this.sku = sku; 
    this.name = name; 
    this.quantity = quantity; 
    this.cost = cost; 
} 

function bundler(quantity) { 
    var remainder = quantity; 
    var bundle = []; 
    while (remainder > 0) { 
     if (remainder >= 10){ 
      var box_10 = new product(3333,"Box of 10",1,1500); 
      bundle.push(box_10); 
      remainder = remainder - 10; 
     } 
     if (remainder >= 5 && remainder <= 9) 
     { 
      var box_5 = new product(2222,"Box of 5",1,1000); 
      bundle.push(box_5); 
      remainder = remainder - 5; 
     } 
     if (remainder <=4 && remainder > 0){ 
      var box_1 = new product(1111,"Box of 1",remainder,250); 
      bundle.push(box_1); 
      remainder = remainder - 1; 
     } 
    } 
    return bundle; 
} 

alert(bundler(22).length); 

Fiddle

+0

Abhishek,非常感謝你!比較你的代碼,看起來像我在正確的道路上,只是在錯誤的地方有一些邏輯! –