Skip to content

Instantly share code, notes, and snippets.

@bay007
Forked from glcheetham/strategy-pattern.js
Last active May 19, 2017 05:31
Show Gist options
  • Save bay007/8e90b0c42b0fd6c25fae5b10648e9258 to your computer and use it in GitHub Desktop.
Save bay007/8e90b0c42b0fd6c25fae5b10648e9258 to your computer and use it in GitHub Desktop.
Strategy Pattern JS example
// Example. Let's sort the apples, pears, and oranges into the right baskets.
const fruits = ["apple", "pear", "apple", "apple", "orange", "pear", "orange", "pear", "apple"]
let appleBasket = []
let pearBasket = []
let orangeBasket = []
let strategies = []
const appleSortStrategy = (fruit) => {
if(fruit === "apple") {
appleBasket.push(fruit)
}
}
strategies.push(appleSortStrategy)
const pearSortStrategy = (fruit) => {
if(fruit === "pear") {
pearBasket.push(fruit)
}
}
strategies.push(pearSortStrategy)
const orangeSortStrategy = (fruit) => {
if(fruit === "orange") {
orangeBasket.push(fruit)
}
}
strategies.push(orangeSortStrategy)
fruits.map(fruit=>{
strategies.map(strategy=>strategy(fruit))
})
console.log(appleBasket) // ["apple", "apple", "apple", "apple"]
console.log(pearBasket) // ["pear", "pear", "pear"]
console.log(orangeBasket) // ["orange", "orange"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment