Last active
September 2, 2016 21:04
-
-
Save SeanLF/5ac8fdbc0df8fd2cb155 to your computer and use it in GitHub Desktop.
Shopify developer intern application task solution [Summer 2016]
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
// Global variables | |
var CATEGORIES_SEARCHED_FOR = ['Keyboard', 'Computer'], MAXIMUM_WEIGHT/*in grams*/ = 100*1000; | |
function get_maximum_number_of_items_for_categories_searched_for_under_maximum_weight(variants, maximum_weight){ | |
var current_weight = 0, subtotal = 0, items = {}; | |
for(index = 0, variants_length = variants.length; index < variants_length; index++){ | |
if(current_weight + variants[index].grams < maximum_weight){ | |
items[variants[index].id] = 1; | |
current_weight += variants[index].grams; | |
} else{break;} | |
} | |
return items; | |
} | |
function update_cart(items){ | |
$.ajax({ | |
type: "POST", | |
url: "http://shopicruit.myshopify.com/cart/update.js", | |
data: {updates: items}, | |
dataType: "json", | |
async: false, | |
error: function(){console.log("Failed to add items to the cart.")} | |
}); | |
} | |
function run_shopicruit_task(){ | |
// Get all products and add to cart | |
$.ajax({ | |
dataType: "json", url: "https://shopicruit.myshopify.com/products.json", async: false, | |
success: function (data) { | |
// Filter products to categories searched for | |
var products = data.products.filter(function(product){ | |
return ~CATEGORIES_SEARCHED_FOR.indexOf(product.product_type); | |
}); | |
// Get all product variants | |
var variants = [].concat.apply([], products.map(function(product){ return product.variants; })); | |
// Sort variants by weight | |
variants.sort(function(a, b){ return a.grams - b.grams; }); | |
// Get the maximum number of product variants under the maximum weight | |
var items = get_maximum_number_of_items_for_categories_searched_for_under_maximum_weight(variants, MAXIMUM_WEIGHT); | |
// Update the cart | |
update_cart(items); | |
}, | |
error: function(){console.log("Failed to get products.");} | |
}); | |
// Get the cart, containing | |
$.getJSON("http://shopicruit.myshopify.com/cart.js", function(data){ | |
console.log(data); | |
console.log("Your order comprises of " + data.item_count + " items for the total price of $" + (data.total_price/100) + | |
". Your items have a total weight of " + (data.total_weight/1000) + "kg." ); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used Shopify's Ajax API
For this code to run, it is assumed that jQuery is available and that it is executing from the Shopicruit Shopify recruitment page.