Skip to content

Instantly share code, notes, and snippets.

@lyninx
Last active January 15, 2016 20:32
Show Gist options
  • Save lyninx/bebbb0597f00ab7c5861 to your computer and use it in GitHub Desktop.
Save lyninx/bebbb0597f00ab7c5861 to your computer and use it in GitHub Desktop.
<html>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="shopicruit.js"></script>
</body>
</html>
/**
* Shopify 'Shopicruit' Task
* author: Dennis Pacewicz
* created: January 14, 2016
*
* Requires JQuery for fetching JSON data
* NOTE: this script assumes that atleast one of each desired item may be purchased without going over carrying capacity (doesn't require a greedy algorithm for selecting items)
**/
var url = "http://shopicruit.myshopify.com/products.json"
var taxRate = 1.13
var weight = 0
var cost = 0
var maxWeight = 100000
var lightest
$.getJSON(url, function (jsonData) {
jsonData.products.forEach(function(elem, index, arr){
var product = elem
// filter json data for desired product types
if(product.product_type == "Computer" || product.product_type == "Keyboard"){
console.log(product.title)
elem.variants.forEach(function(elem, index, arr){
console.log(" > " + elem.id + " " + elem.title + " " + elem.price + " " + elem.grams)
// find which product variant is the lightest
if(lightest == undefined || elem.grams < lightest.grams){
lightest = elem
}
weight += elem.grams
purchase(elem)
})
}
})
// purchase as many of the lightest item as possible until we've met carrying capacity
while((weight + lightest.grams) < maxWeight){
weight += lightest.grams
purchase(lightest)
}
console.log("carrying: " + weight / 1000 + " kg")
console.log("cost total: $" + cost / 100)
});
// sum up the cost of the items, and add tax if applicable
function purchase(elem){
cost += (function(){
if(elem.taxable == false){
return (parseFloat(elem.price) * 100)
}
else {
return (Math.ceil(parseFloat(elem.price) * taxRate * 100))
}
})()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment