Created
December 2, 2021 15:07
-
-
Save sebastiancarlos/0d30b64b79196011ec0b170a7eb1e68c to your computer and use it in GitHub Desktop.
Interface to buy food from the supermarket.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// interface for food | |
interface Food { | |
name: string; | |
calories: number; | |
} | |
// interface for refrigerator | |
interface Refrigerator { | |
food: Food[]; | |
addFood(food: Food): void; | |
getFood(foodName: string): Food | undefined; | |
} | |
// interface for supermarket | |
interface Supermarket { | |
food: Food[]; | |
buyFood(foodName: string): Food | undefined; | |
} | |
// initialize refrigerator | |
let refrigerator: Refrigerator = { | |
food: [], | |
addFood(food: Food) { | |
this.food.push(food); | |
}, | |
getFood(foodName: string) { | |
let food = this.food.find((food) => food.name === foodName); | |
if (food) { | |
this.food.splice(this.food.indexOf(food), 1); | |
return food; | |
} | |
}, | |
}; | |
// initialize supermarket | |
let supermarket: Supermarket = { | |
food: [], | |
buyFood(foodName: string) { | |
let food = this.food.find((food) => food.name === foodName); | |
if (food) { | |
this.food.splice(this.food.indexOf(food), 1); | |
return food; | |
} | |
}, | |
}; | |
// if there is no 'pineapple' buy it from the supermarket. | |
if (!refrigerator.getFood("pineapple")) { | |
const pineapple = supermarket.buyFood("pineapple"); | |
if (pineapple) { | |
refrigerator.addFood(pineapple); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment