[JavaScript] all combinations + bitmask
Key point:\n- how to generate all possible topping combinations?\n- bitmask: to choose 1 or 0 toppings\n- array + array -> choose 2 or 1 or 0 toppings\n\nBecaus
Key point:\n- how to generate all possible topping combinations?\n- bitmask: to choose 1 or 0 toppings\n- array + array -> choose 2 or 1 or 0 toppings\n\nBecause I don\'t have a clean and smart way to do the 2 toppings also with bitmask, so i just do it in a stupid and brute force way:\n```\nfor( c1  of cost)\n\tfor(c2 of cost)\n\t{   // pick 2 or 1 or 0 toppings\n\t\t\ttoppingCost = c1 + c2; \n\t}\n```\n\nSolution:\n```js\nvar closestCost = function(baseCosts, toppingCosts, target) {\n    // topping cost: 2^m  - pick zero or one \n    var m = toppingCosts.length;\n    var diff = Infinity;\n    var res = 0;\n    var cost = [];\n    for(var i = 0; i< 1<<m; i++)\n    {\n       var sum = 0;\n        for(var j = 0; j<m;j++)\n        {\n            if( ((i >> j)  & 1 )=== 1)\n            {\n                sum += toppingCosts[j];\n            }\n        }\n       cost.push(sum);\n    }\n    \n    // same array add itself: pick 2 or 1 or 0 toppings\n    for(var c1 of cost)\n        for(var c2 of cost)\n        {\n             var c = c1+c2;\n             for(var base of baseCosts)\n             {   \n                if(Math.abs(target - base - c) === diff)\n                {\n                    res = base + c < res ? base+c: res;\n                }\n                else if(Math.abs(target - base - c) < diff)\n                {\n                    res = base + c;\n                    diff = Math.abs(target-base-c);\n                }\n            }\n        }\n    return res;  \n};\n```
['JavaScript']