Created
January 24, 2019 09:17
-
-
Save radmen/1954f970ae0e106320144b28e4693511 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
const deepEql = require('deep-eql') | |
const input = require('./input.json') | |
const output = require('./output.json') | |
const groupByDate = (messages) => messages.reduce( | |
(carry, message) => { | |
const copy = Array.from(carry) | |
const tail = copy.pop(); | |
const groupDate = new Date(message.created_at).getDate(); | |
return tail && tail[0].groupDate === groupDate | |
? copy.concat([tail.concat({ groupDate, ...message })]) | |
: carry.concat([[{ groupDate, ...message }]]) | |
}, | |
[] | |
); | |
const groupByUser = (messages) => messages.reduce( | |
(carry, message) => { | |
const copy = Array.from(carry) | |
const tail = copy.pop() | |
const { groupDate, ...rest } = message | |
if (!tail || tail.user.id !== rest.user.id) { | |
return carry.concat({ ...rest, children: [rest] }) | |
} | |
return copy.concat({ ...tail, children: tail.children.concat(rest) }) | |
}, | |
[] | |
) | |
const combineMessages = (messages) => { | |
const byDate = groupByDate(messages) | |
return byDate.map(items => ({ | |
date: items[0].created_at, | |
messages: groupByUser(items) | |
})) | |
} | |
const result = _combineMessages(input) | |
if (!deepEql(output, result)) { | |
console.log(JSON.stringify(result)) | |
} else { | |
console.log('ok!') | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment