Skip to content

Instantly share code, notes, and snippets.

@SeanPlusPlus
Created June 9, 2017 19:41
Show Gist options
  • Save SeanPlusPlus/93db2fead40b2d1be046417cd58b922e to your computer and use it in GitHub Desktop.
Save SeanPlusPlus/93db2fead40b2d1be046417cd58b922e to your computer and use it in GitHub Desktop.
The Scrambler
import request from 'request'
import money from 'money-math'
// This:
// const b64string = 'R3Vlc3MgeW91IHJlYWxseSBhcmUgdXAgZm9yIGEgY2hhbGxlbmdlLiBHZXQgdGhlIGNvbWJpbmVkIHRvdGFsIGNvc3Qgb2YgdGhlIHR3byBtb3N0IGV4cGVuc2l2ZSBwcm9kdWN0cyBhbmQgdGhlIHR3byBsZWFzdCBleHBlbnNpdmUgcHJvZHVjdHMgYXQgdGhpcyBlbmRwb2ludCwgYW5kIHRoZXJlJ3MgeW91ciBhbnN3ZXI6IGh0dHA6Ly93d3cuY29kZXdpdGh0YXJnZXQuY29tL2Fzc2V0cy9kYXRhL3RoZS1zY3JhbWJsZXIuanNvbg=='
// const buf = Buffer.from(b64string, 'base64')
// console.log(buf.toString())
// Produces this:
// Get the combined total cost of the two most expensive products
// and the two least expensive products at this endpoint
const url = 'https://www.codewithtarget.com/assets/data/the-scrambler.json'
// Hit the end point and parse
request(url, function (error, response, body) {
const products = JSON.parse(body)
// Set the initial price to that of the first product in the list
const initial = products[0].price.split('$')[1]
const expensive = {
first: initial,
second: initial,
}
const cheapest = {
first: initial,
second: initial,
}
// Now walk thru products
products.forEach(p => {
const price = p.price.split('$')[1]
// Is this first or second most expensive
if ((money.cmp(price, expensive.first)) > 1) {
expensive.second = expensive.first
expensive.first = price
} else if ((money.cmp(price, expensive.second)) > 1) {
expensive.second = price
}
// Is this first or second cheapest
if ((money.cmp(price, cheapest.first)) < 1) {
cheapest.second = cheapest.first
cheapest.first = price
} else if ((money.cmp(price, cheapest.second)) < 1) {
cheapest.second = price
}
})
const ans = money.add(
money.add(expensive.first, expensive.second),
money.add(cheapest.first, cheapest.second)
)
console.log('Answer: $' + ans)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment