Skip to content

Instantly share code, notes, and snippets.

@juque
Forked from ismasan/cart-info.js
Created September 26, 2016 22:41
Show Gist options
  • Save juque/2e32d263b8113b7025129731b400306a to your computer and use it in GitHub Desktop.
Save juque/2e32d263b8113b7025129731b400306a to your computer and use it in GitHub Desktop.
Collect product information for products in a Bootic cart
/* Collect product information for products in the cart
Usage:
Get all products in the cart
CartInfo.getProducts(function (products) {
// products is an array of product objects
console.log(products)
})
Get an object with aggregated data from products in cart
CartInfo.getInfo(function (info) {
// all collections in cart
console.log('collections', info.collections)
// all types in cart
console.log('types', info.types)
// all tags in cart
console.log('tags', info.tags)
// all vendors in cart
console.log('vendors', info.vendors)
})
*/
var CartInfo = (function ($){
function collectProductSlugs (cart) {
return cart.products.map(function(p){return p.slug});
}
function startProductRequests (slugs) {
return slugs.map(function(s){
return $.getJSON("/products/"+s+".json")
})
}
function waitForAllRequests (promises) {
return $.when.apply($, promises)
}
function mapJsonObjectsFromResponses () {
var arr = Array.prototype.slice.call(arguments)
return arr.map(function (a) { return a[0]})
}
function productCollections(memo, prod) {
return memo.concat(prod.collections)
}
function flatten(listName) {
return function (memo, prod) {
return memo.concat(prod[listName])
}
}
function pluck(field) {
return function (memo, prod) {
if(prod[field])
memo.push(prod[field]);
return memo;
}
}
function fetchProductsInCart() {
return $.getJSON("/cart.json")
.then(collectProductSlugs)
.then(startProductRequests)
.then(waitForAllRequests)
.then(mapJsonObjectsFromResponses);
}
function getProducts (fn) {
fetchProductsInCart().then(fn)
}
function getInfo (fn) {
fetchProductsInCart().then(function (products) {
var collections = products.reduce(flatten("collections"), [])
var types = products.reduce(pluck("product_type"), []);
var vendors = products.reduce(pluck("vendor_name"), []);
var tags = products.reduce(flatten("tags"), []);
fn({
collections: collections,
types: types,
vendors: vendors,
tags: tags
})
});
}
return {
getProducts: getProducts,
getInfo: getInfo
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment