Skip to content

Instantly share code, notes, and snippets.

@anupvarghese
Last active December 17, 2019 04:35
Show Gist options
  • Save anupvarghese/9f75d80f176818d31c78b2b004e630db to your computer and use it in GitHub Desktop.
Save anupvarghese/9f75d80f176818d31c78b2b004e630db to your computer and use it in GitHub Desktop.
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