Last active
September 30, 2016 03:19
-
-
Save ismasan/3ae6b8b592d9d5c8cc9da9ad63d7beff to your computer and use it in GitHub Desktop.
Collect product information for products in a Bootic cart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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
El siguiente código impide pasar al checkout y muestra una alerta si es que el carro no incluye la colección "Ofertas"