Skip to content

Instantly share code, notes, and snippets.

@blakehaswell
Created June 27, 2012 12:09
Show Gist options
  • Save blakehaswell/3003674 to your computer and use it in GitHub Desktop.
Save blakehaswell/3003674 to your computer and use it in GitHub Desktop.
Deduplicate coffees code
var beverage = {
"SB" : "Short black",
"LB" : "Long black",
"Cap" : "Cappuccino",
"FW" : "Flat white"
};
var milk = {
"reg" : "Regular",
"soy" : "Soy milk",
"skim" : "Skim milk"
}
var Coffee = function (beverage, milk, shots, sugars) {
this.beverage = beverage;
this.milk = milk;
this.shots = shots;
this.sugars = sugars;
this.count = 1;
};
Coffee.prototype = {
isEqual: function (coffee) {
return this.beverage === coffee.beverage
&& this.milk === coffee.milk
&& this.shots === coffee.shots
&& this.sugars === coffee.sugars;
}
}
var coffees = [
new Coffee("SB", "skim", 1, 2),
new Coffee("LB", "reg" , 2, 2),
new Coffee("LB", "skim", 1, 1),
new Coffee("SB", "skim", 1, 2)
];
console.log("Coffees:");
console.log(coffees);
function coffeeInArray(coffee, array) {
for (var i = 0, l = array.length; i < l; ++i) {
if (coffee.isEqual(array[i])) {
return array[i];
}
}
return false;
}
function dedupCoffees(coffees) {
var newCoffees = [];
var coffee;
for (var i = 0, l = coffees.length; i < l; ++i) {
coffee = coffeeInArray(coffees[i], newCoffees);
if (coffee) {
coffee.count += 1;
} else {
newCoffees.push(coffees[i]);
}
}
return newCoffees;
}
coffees = dedupCoffees(coffees);
console.log("Deduplicated coffees:");
console.log(coffees);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment