Skip to content

Instantly share code, notes, and snippets.

@fuunnx
Last active October 3, 2019 20:55
Show Gist options
  • Save fuunnx/77ac32d3c0e27f299062c323efa68c89 to your computer and use it in GitHub Desktop.
Save fuunnx/77ac32d3c0e27f299062c323efa68c89 to your computer and use it in GitHub Desktop.
const data = [
{ name: "chocolat pépites", price: 2.81 },
{ name: "pulco", price: 2.58 },
{ name: "ampoule 1", price: 5.4 },
{ name: "ampoule 2", price: 2.57 },
{ name: "emmental", price: 2.58 },
{ name: "emmental", price: 2.58 },
{ name: "comté", price: 4.94 },
{ name: "courgette", price: 0.55 },
{ name: "chanterelles", price: 3.49 }
];
const elligible = 11.56;
function find(target, availables) {
return availables.reduce((combinations, option, index) => {
const { price } = option;
if (price === target) {
combinations.push([option]);
return combinations;
}
if (price < target) {
const tail = availables.slice(index + 1);
const remainder = target - price;
const subcombinations = find(remainder, tail);
combinations.push(
...subcombinations.map(combination => [option, ...combination])
);
return combinations;
}
return combinations;
}, []);
}
const combinations = find(elligible, data);
console.log(combinations);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment