Skip to content

Instantly share code, notes, and snippets.

@glcheetham
Last active December 13, 2017 22:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save glcheetham/a056d9ac9fe922978423a3e0533d4e17 to your computer and use it in GitHub Desktop.
Save glcheetham/a056d9ac9fe922978423a3e0533d4e17 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.forEach((fruit) => {
strategies.forEach((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