diff --git "a/DesignPattern/1-\345\215\225\344\276\213\346\250\241\345\274\217.md" "b/DesignPattern/1-\345\215\225\344\276\213\346\250\241\345\274\217.md" index 3d643ac..cd0f9bd 100644 --- "a/DesignPattern/1-\345\215\225\344\276\213\346\250\241\345\274\217.md" +++ "b/DesignPattern/1-\345\215\225\344\276\213\346\250\241\345\274\217.md" @@ -506,7 +506,7 @@ const PRIVATE_KEY = Symbol(); class ShoppingCartManagerJS { static #instance; - #products = []; + #products = new Map(); constructor(key) { if (key !== PRIVATE_KEY) { @@ -522,15 +522,20 @@ class ShoppingCartManagerJS { } add(name, quantity) { - this.#products.push({ name, quantity }); + if(this.#products.has(name)){ + this.#products.set(name, this.#products.get(name) + quantity); + return; + }else{ + this.#products.set(name, quantity); + } } viewCart() { - if (this.#products.length === 0) { + if (this.#products.size === 0) { return; } - this.#products.forEach((product) => { - console.log(`${product.name} ${product.quantity}`); + this.#products.forEach((quantity, name) => { + console.log(`${name} ${quantity}`); }); } }