From 09807ca36232987f8cb0b359fde4ab0d0c20338e Mon Sep 17 00:00:00 2001 From: Leonardo Matos Date: Sat, 25 Jan 2020 18:52:49 -0300 Subject: [PATCH] feat(reset): add new 'reset' method --- src/constructor.js | 5 +++++ src/methods/reset.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/methods/reset.js diff --git a/src/constructor.js b/src/constructor.js index 46eb224..e2d730b 100644 --- a/src/constructor.js +++ b/src/constructor.js @@ -7,6 +7,7 @@ import increaseItemQnt from './methods/increase-item-qnt' import removeItem from './methods/remove-item' import save from './methods/save' import clear from './methods/clear' +import reset from './methods/reset' const defaultStorage = typeof window === 'object' && window.localStorage @@ -121,6 +122,10 @@ const EcomCart = function (storeId, storageKey = 'ecomShoppingCart', localStorag return methodsMiddleware(clear, [canSave]) } + this.reset = (canSave) => { + return methodsMiddleware(reset, [canSave]) + } + this.save = (canFixSubtotal) => { return methodsMiddleware(save, [canFixSubtotal], false) } diff --git a/src/methods/reset.js b/src/methods/reset.js new file mode 100644 index 0000000..ebea9fe --- /dev/null +++ b/src/methods/reset.js @@ -0,0 +1,39 @@ +import { randomObjectId } from '@ecomplus/utils' + +/** + * @method + * @name EcomCart#reset + * @description Reset all cart data and create new random ID. + * + * @param {boolean} [canSave=true] - Save new cart to local storage + * + * @returns {self} + * + * @example + +ecomCart.reset() + + */ + +export default (self, emitter, [canSave = true]) => { + let { data, save } = self + + data = { + _id: randomObjectId(), + items: [], + subtotal: 0 + } + + /** + * @event EcomCart#reset + * @type {object} + * @property {object} data - Shopping cart data + * @example ecomCart.on('reset', ({ data }) => { console.log(data._id) }) + */ + emitter.emit('reset', { data }) + + if (canSave) { + save(false) + } + return self +}