Last active
September 28, 2016 09:14
-
-
Save oandrienko/d6122b546c5b236b0e369fc3a5a0cc4a to your computer and use it in GitHub Desktop.
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
//Oles Andrienko 2016 - for Shopify Jobmine application | |
import path from 'path'; | |
import clc from 'cli-color'; | |
import request from 'request'; | |
import async from 'async'; | |
//import pageTotal from './utils'; | |
/** | |
* Task: Calculate the total cost of all watches and clocks from the | |
* shopicruit.myshopify.com store. | |
* -> Assuming we are counting all the variants of each watch/clock | |
*/ | |
const baseUrl = 'http://shopicruit.myshopify.com/products.json?page=', | |
synonyms = [/watch/, /clock/, /timer/, /ticker/, /time/]; | |
let count = 0, total = 0, products = [null], page = 1; | |
console.log('Calculating Watch/Clock Product total...'); | |
/** | |
* Utils... | |
*/ | |
const checkMatch = (val, arr) => { | |
for(var i = 0; i < arr.length; i++) { | |
if (val.toLowerCase().match(arr[i]) != null) { | |
return true; | |
} | |
} | |
return false; | |
}; | |
const pageTotal = (products, synonyms) => { | |
let cost = 0; | |
for (var i = 0; i < products.length; i++) { | |
if (checkMatch(products[i].title, synonyms)) { | |
// console.log('success, watch found in ' + products[i].title); | |
for (var j=0; j < products[i].variants.length; j++){ | |
cost += Number(products[i].variants[j].price); | |
} | |
} | |
} | |
return cost; | |
}; | |
/** | |
* Main | |
*/ | |
async.whilst( | |
() => products.length > 0, | |
next => { | |
request(baseUrl + page, (error, response, body) => { | |
if (!error && response.statusCode == 200){ | |
products = JSON.parse(body).products; | |
total += pageTotal(products, synonyms); | |
} | |
page++; | |
next(null, page); | |
}); | |
}, | |
error => { | |
error === null | |
? console.log(clc.green.bold('\tStore total: $', Math.round(total*100)/100)) | |
: console.log(clc.red.bold('An error occured: ', error)); | |
console.log('Done!'); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment