-
-
Save bay007/8e90b0c42b0fd6c25fae5b10648e9258 to your computer and use it in GitHub Desktop.
Strategy Pattern JS example
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
// 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