2 回答
TA贡献1848条经验 获得超2个赞
解决了这个 O(n) 解决方案
sortedCAarray.forEach((act, index) => {
const currActivityTime = moment(act.timestamp).valueOf()
console.log(currActivityTime)
// First element is already added, avoid duplicates
if (index < 1) return
// Grab the last key from the timestampMap
const timestampKeys = Object.keys(timestampMap)
const key = timestampKeys[timestampKeys.length - 1]
// Add the activity and purpose to the respective arrays and set for that key if the key is within 5 units of the current activity timestamp
if (Math.abs(key - currActivityTime) < 5) {
let activities = timestampMap[key].activities
let purposes = timestampMap[key].purposes
activities.push(act)
purposes.add(act.purpose)
let timestamp = moment(activities[activities.length - 1].timestamp).valueOf()
// Edge case to to include all activities in the same bucket if they were within 5 ms of any element within the bucket
if (timestamp > key) {
Object.defineProperty(timestampMap, timestamp,
Object.getOwnPropertyDescriptor(timestampMap, key))
delete timestampMap[key]
}
} else {
// If not just create a new key with the current activity timestamp as the key
timestampMap[currActivityTime] = { activities: [act], purposes: new Set([act.purpose]) }
}
})
希望对此有任何改进!谢谢
添加回答
举报