Skip to content

Instantly share code, notes, and snippets.

@rmoskal
Last active December 5, 2017 21:40
Show Gist options
  • Save rmoskal/ffa7f2500367fbe5c0b29829e4dbec90 to your computer and use it in GitHub Desktop.
Save rmoskal/ffa7f2500367fbe5c0b29829e4dbec90 to your computer and use it in GitHub Desktop.
async_harmful_v1 created by rmoskal - https://repl.it/@rmoskal/asyncharmfulv1
/**
Takes this incoming array
[ { team: 'blue',
sales: 900,
userId: 'a0bc44d0-da95-495d-bcf2-535d0b9d8af3',
name: 'Sally Smith' },
{ team: 'blue',
sales: 800,
userId: 'c509388c-9321-4fab-8062-3fa56b2b0d87',
name: 'John Jones' } ]
And tranforms it into the following object:
{ team: 'blue',
sales: 1700,
users:
[ { sales: 900,
userId: 'a0bc44d0-da95-495d-bcf2-535d0b9d8af3',
name: 'Sally Smith' },
{ sales: 800,
userId: 'c509388c-9321-4fab-8062-3fa56b2b0d87',
name: 'John Jones' } ] }
**/
function functionalWay(color) {
fetch(color)
.then(resultsString =>JSON.parse(resultsString))
.then(jsonResults => transformFirst(jsonResults))
.then(transformResults => sendToClient(transformResults))
.then(sendResults => remotelog('log',sendResults))
.catch(err => remotelog('error', err))
}
async function declarativeWay(color) {
try {
let resultsString = await fetch(color)
let jsonResults=JSON.parse(resultsString);
let transformResults= transformFirst(jsonResults)
let sendResults = await sendToClient(transformResults)
remotelog('log', sendResults)
}catch (e) {
remotelog('error', e)
}
}
functionalWay('blue')
declarativeWay('blue')
//The functions!
function fetch(color) {
let data = [
{
"team": "blue",
"sales": 900,
"userId": "a0bc44d0-da95-495d-bcf2-535d0b9d8af3",
"name": "Sally Smith"
},
{
"team": "blue",
"sales": 800,
"userId": "c509388c-9321-4fab-8062-3fa56b2b0d87",
"name": "John Jones"
},
{
"team": "red",
"sales": 200,
"userId": "c509388c-9321-4fab-8062-3fa56b2b0d66",
"name": "Joey Ramone"
}
]
return Promise.resolve(JSON.stringify(data.filter(each => each.team == color)))
}
function sendToClient(payload) {
return Promise.resolve({status:'ok'})
}
function remotelog(level, msg) {
console[level](msg)
}
function transformFirst(_in){
let res = Object.assign({}, _in[0])
res.users = _in.map(each => {return {sales:each.sales,
userId:each.userId,
name: each.name
}} )
delete res.userId
delete res.name
res.sales = res.users.reduce((accum, each) => accum + each.sales, 0)
return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment