Created
January 22, 2022 20:53
-
-
Save enigma1/08597ef04b07885701c0955f81c12574 to your computer and use it in GitHub Desktop.
Example of a visitor pattern in js
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
| // Visitor Pattern | |
| // Some existing raw data to be altered | |
| const cars = [ | |
| ["Ford Escort", 10000, 50], | |
| ["Fiat Panda", 20000, 42], | |
| ["VW Polo", 25000, 59], | |
| ["BMW 320", 100000, 10], | |
| ["Dodge Viper", 200000, 3], | |
| ["Honda Civic", 21000, 33] | |
| ]; | |
| // The main Car object coordinates the changes | |
| const Car = props => { | |
| let {name, value, stock} = props; | |
| const ifc = { | |
| update: change => change(ifc), // Special methods invoke existing ones for the update | |
| // Set of standard functions for processing existing data | |
| getName: () => name, | |
| getValue: () => value, | |
| getStock: () => stock, | |
| setValue: price => value = price, | |
| setStock: qty => stock = qty | |
| } | |
| return ifc; | |
| }; | |
| // Special methods to apply | |
| const Discounted = () => car => car.setValue(car.getValue()*0.8); | |
| const HighStock = () => car => car.setStock(car.getStock()*2); | |
| // Test cycle | |
| const test = () => { | |
| // Create a list of elements using the raw input data | |
| const carMap = cars.map(([name, value, stock]) => Car({name, value, stock})) | |
| // Special methods utilized here | |
| const discountedValue = Discounted(); | |
| const extraStock = HighStock(); | |
| // Apply the changes and show the result | |
| for (const vehicle of carMap) { | |
| vehicle.update(discountedValue); | |
| vehicle.update(extraStock); | |
| console.log( | |
| vehicle.getName() + " now costs only $" + | |
| vehicle.getValue() + " and " + | |
| vehicle.getStock() + " cars available" | |
| ); | |
| } | |
| } | |
| test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment