Last active
November 28, 2018 09:28
-
-
Save jcyh0120/ca29f69912acc935fbfef4f7098f6201 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 getRandomTime = () => Math.floor(Math.random() * 10000) | |
const time = Date.now() | |
const data = [ | |
{ timestamp: time + getRandomTime(), message: 'hello1', user: 'user1' }, | |
{ timestamp: time + getRandomTime(), message: 'hello2', user: 'user2' }, | |
{ timestamp: time + getRandomTime(), message: 'hello3', user: 'user3' }, | |
{ timestamp: time + getRandomTime(), message: 'hello4', user: 'user1' }, | |
{ timestamp: time + getRandomTime(), message: 'hello5', user: 'user2' }, | |
{ timestamp: time + getRandomTime(), message: 'hello6', user: 'user3' }, | |
{ timestamp: time + getRandomTime(), message: 'hello7', user: 'user1' }, | |
{ timestamp: time + getRandomTime(), message: 'hello8', user: 'user2' }, | |
{ timestamp: time + getRandomTime(), message: 'hello9', user: 'user3' }, | |
{ timestamp: time + getRandomTime(), message: 'hello10', user: 'user1' } | |
] | |
const start = time | |
const end = time + 5 * 1000 | |
const duration = 1000 | |
const users = ['user1', 'user2'] | |
let expectResponse = [] | |
for (let i = start; i <= end; i += duration) { | |
let usersCount = [] | |
for (let user of users) { | |
const messageCount = data.reduce((counts, message) => { | |
if ( | |
message.timestamp >= i && | |
message.timestamp < i + duration && | |
message.user === user | |
) { | |
return counts + 1 | |
} else { | |
return counts | |
} | |
}, 0) | |
usersCount.push({ id: user, count: messageCount }) | |
} | |
expectResponse.push({ | |
start: i, | |
messagesCount: usersCount | |
}) | |
} | |
/* Output Data Format | |
[ | |
{ | |
start: 12344444 | |
messagesCount:[ | |
{id:'user1',count:2}, | |
{id:'user2',count:4}, | |
{id:'user3',count:5} | |
] | |
}, | |
{ | |
start: 12354444, | |
{id:'user1',count:1}, | |
{id:'user2',count:1}, | |
{id:'user3',count:0} | |
}, | |
{ | |
start: 12364444, | |
{id:'user1',count:3}, | |
{id:'user2',count:2}, | |
{id:'user3',count:1} | |
} | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment