Code Monkey home page Code Monkey logo

cart-localstorage's Introduction

cart-localstorage

Super simple JavaScript shopping cart library

This micro library (2.2Kb) utilizes the browser's localStorage to create a persistent shopping cart instance.

Demo

Cart demo

Install:

Use npm or yarn to add it to your ES6 project:

npm install cart-localstorage
yarn add cart-localstorage
import { add, total } from 'cart-localstorage' 

add({id: 1, name: "Product 1", price: 100})
add({id: 2, name: "Product 2", price: 100}, 2)

console.log(total()) 
// output: 300

Bundled version (ES5) via CDN:

<script src="https://unpkg.com/[email protected]/dist/cart-localstorage.min.js" type="text/javascript"></script>
cartLS.add({id: 1, name: "Product 1", price: 100})
cartLS.add({id: 2, name: "Product 2", price: 100}, 2)

console.log(cartLS.total()) 
// output: 300

Documentation

add(product, [quantity:1])

Adds product to the cart. If the product already exists it increases the quantity with 1. The product object structure is flexible, only "id" and "price" are mandatory properties.

const myproduct = {id: 3, name: "Vans", price: 75}
add(myproduct, 2)

get(id)

Get product from the cart by id

get(1)
// {id: 1, name: "Nike Air", price: 100, quantity: 1}

exists(id)

Checks if the product already exists in the cart

exists(21)
// true or false

list()

Get the content of the cart as an array of products.

list()
// [{id: 1, name: "Nike Air", price: 100, quantity: 1}, {id: 2, name: "Adidas Superstar", price: 120, quantity: 2}]

remove(id)

Removes the product from the cart

remove(1)

update(id, property, value)

Updates the product's property with a certain value.

update(1,'price',200)

quantity(id, diff)

Increase / decrease product's quantity with a positive or negative value.

quantity(22,-1) // will decrease the quantity of product [id:22] with 1.

total([reducer])

By default returns with the total price:

total()
// 220

or you can pass a custom reducer function to summarize other attributes, like product quantity:

total((sum, product) => (sum += product.quantity), 0)

destroy()

Deletes the cart array from the browser's localStorage.

destroy()

License

This library is available under MIT license.

cart-localstorage's People

Contributors

dependabot[bot] avatar peet86 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

cart-localstorage's Issues

Changing __cart as localstorage name

I am loading the cart-localstorage.min.js on my own server and not via the CDN but i want to change the localstorage name __cart into __cart2. I did it in this file but i got an error 'cartLS is not defined'. Can you tell me what i am doing wrong?

I only changed the bold line:

var cartLS = (function (a) {
"use strict";
function b(a, b, c) {
return b in a ? Object.defineProperty(a, b, { value: c, enumerable: !0, configurable: !0, writable: !0 }) : (a[b] = c), a;
}
function c(a, b) {
var c = Object.keys(a);
if (Object.getOwnPropertySymbols) {
var d = Object.getOwnPropertySymbols(a);
b &&
(d = d.filter(function (b) {
return Object.getOwnPropertyDescriptor(a, b).enumerable;
})),
c.push.apply(c, d);
}
return c;
}
function d(a) {
for (var b, d = 1; d < arguments.length; d++)
(b = null == arguments[d] ? {} : arguments[d]),
d % 2
? c(b, !0).forEach(function (c) {
f(a, c, b[c]);
})
: Object.getOwnPropertyDescriptors
? Object.defineProperties(a, Object.getOwnPropertyDescriptors(b))
: c(b).forEach(function (c) {
Object.defineProperty(a, c, Object.getOwnPropertyDescriptor(b, c));
});
return a;
}
var e = (function (a, b) {
return (b = { exports: {} }), a(b, b.exports), b.exports;
})(function (a) {
function b(a) {
return (
(b =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function (a) {
return typeof a;
}
: function (a) {
return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : typeof a;
}),
b(a)
);
}
function c(d) {
return (
(a.exports =
"function" == typeof Symbol && "symbol" === b(Symbol.iterator)
? (c = function (a) {
return b(a);
})
: (c = function (a) {
return a && "function" == typeof Symbol && a.constructor === Symbol && a !== Symbol.prototype ? "symbol" : b(a);
})),
c(d)
);
}
a.exports = c;
}),
f = b,
g = "__cart2",
h = null,
i = function (a) {
h = a;
},
j = function (a) {
return JSON.parse(localStorage.getItem(a || g)) || [];
},
k = function (a, b) {
localStorage.setItem(b || g, JSON.stringify(a)), h && h(j(b || g));
},
l = function (a) {
localStorage.removeItem(a || g), h && h(j(a || g));
},
m = function (a) {
return j().find(function (b) {
return b.id === a;
});
},
n = function (a) {
return !!m(a);
},
o = function (a) {
return k(
j().filter(function (b) {
return b.id !== a;
})
);
},
p = function (a, b, c) {
return k(
j().map(function (e) {
return e.id === a ? d({}, e, f({}, b, c)) : e;
})
);
},
q = function (a) {
return a.id && a.price;
},
r = function (a) {
return s(a) ? a.price * a.quantity : 0;
},
s = function (a) {
return a && a.price && a.quantity;
},
t = function (a) {
return a && "function" == typeof a;
};
return (
(a.add = function (a, b) {
return q(a) ? (n(a.id) ? p(a.id, "quantity", m(a.id).quantity + (b || 1)) : k(j().concat(d({}, a, { quantity: b || 1 })))) : null;
}),
(a.destroy = function () {
return l();
}),
(a.exists = n),
(a.get = m),
(a.list = j),
(a.onChange = function (a) {
return t(a) ? i(a) : console.log(e(a));
}),
(a.quantity = function (a, b) {
return n(a) && 0 < m(a).quantity + b ? p(a, "quantity", m(a).quantity + b) : o(a);
}),
(a.remove = o),
(a.subtotal = r),
(a.total = function (a) {
return j().reduce(function (b, c) {
return t(a) ? a(b, c) : (b += r(c));
}, 0);
}),
(a.update = p),
a
);
})({}); //# sourceMappingURL=cart-localstorage.min.js.map

Item Does Not Get Added to Cart if Price is 0 / 0.00

Hi,

Items do not seem to get added to the cart if the price is 0 / 0.00.

This makes it difficult / impossible to add 'Free' items to the cart.

Is this expected behaviour? How do I add free items to the cart?

Thanks,
Alex

Updating line item nested objects

When I use the update() is there a way to target nested objects?

For example, here is my line item object:

{
     id: 4133
     nonprofit: {
          name: "Product 1",
          message: "message for someone",
     }
     price: 10
     quantity: 1
}

I wanted to use the update() to change the message within the nonprofit object.

Right now the update() only takes "field" key but how can I access that field within the nested object?

I tried doing this but it just add it as a key within the object update(4133, 'nonprofit.message', 10)

Thanks!

quantity update not working

If i use the cartLS.quantity(id,1); or cartLS.quantity(id,-1); the quantity is going p.e. from 7 by default to 71 instead of 8
What is going wrong?

Abracadabra code

How can I read this code? Why it looks like a complete abracadabra?

can not use with ssr in gatsby

receiving the error "localStorage" is not available during server side rendering when building the app
Any ideas how to solve this problem ?

Add sumQuantity feature

you can add a count() function that return the number of items that are in list()
this function is necessary since with "list().length" we only get the items, we must add the quantity of products

No Function To get Cart Count

I need a function to get the count of cart items as they are being added to cart. Seems the library doesn't have it.

Custom reducer function example for Total

Thank you for this library.

By default returns with the total price:
or you can pass a custom reducer function to have full control over the calculation.

Do you have an example of using a reducer function for total? I'm trying to implement applying "discount" functionality (ie: 10% off the subtotal) but not sure what the best way to implement that would be.

Thank you in advance if you are able to recommend anything.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.