Last active
December 17, 2019 04:35
-
-
Save anupvarghese/9f75d80f176818d31c78b2b004e630db to your computer and use it in GitHub Desktop.
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
type Message = { | |
text: string; | |
type: 'Error' | 'Warning' | 'Info'; | |
}; | |
type Item = { | |
product: string; | |
quantity: number; | |
price: number; | |
total: number; | |
totalGST: number; | |
messages: Array<Message>; | |
minimumQuantity: number; | |
}; | |
type Cart = { | |
lineItems: Array<Item>; | |
totalQuantity: number; | |
total: number; | |
subtotal: number; | |
totalGST: number; | |
messages: Message[]; | |
}; | |
class CartValidation { | |
private _cart: Cart; | |
constructor(cart: Cart) { | |
this._cart = cart; | |
} | |
setErrorMessage(item: Item, message: Message): void { | |
item.messages.push(message); | |
} | |
accept(visitor: Visitor): void { | |
visitor.visit(this); | |
} | |
get cart(): Cart { | |
return this._cart; | |
} | |
set cart(cart) { | |
this._cart = cart; | |
} | |
} | |
interface Visitor { | |
visit(cart: CartValidation): void; | |
} | |
class MinimumQuantityValidation implements Visitor { | |
visit(cartValidation: CartValidation): void { | |
for (const item of cartValidation.cart.lineItems) { | |
if (item.minimumQuantity > item.quantity) { | |
cartValidation.setErrorMessage(item, { text: 'Need more quantity', type: 'Error' }); | |
} | |
} | |
} | |
} | |
const cartValidation = new CartValidation({ | |
lineItems: [{ product: '123', quantity: 10, price: 10, messages: [], minimumQuantity: 20, total: 0, totalGST: 0 }], | |
total: 0, | |
totalGST: 10, | |
totalQuantity: 0, | |
subtotal: 0, | |
messages: [], | |
}); | |
const minimumQuantityValidation = new MinimumQuantityValidation(); | |
cartValidation.accept(minimumQuantityValidation); | |
console.log(cartValidation.cart.lineItems[0].messages); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment