Last active
December 13, 2017 22:27
-
-
Save glcheetham/a056d9ac9fe922978423a3e0533d4e17 to your computer and use it in GitHub Desktop.
Strategy Pattern JS example
This file contains hidden or 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
// 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