Created
January 18, 2019 00:31
-
-
Save protiumx/5e9cfd81c33a6087116c214fccaa099e to your computer and use it in GitHub Desktop.
retrieveUsers.js
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 users = {} | |
function node(key, value) { | |
this.next = null | |
this.prev = null | |
this.key = key | |
this.value = value | |
} | |
let head = null | |
let tail = null | |
function saveUserLogin(userId) { | |
let userNode = users[userId] | |
if (userNode) { | |
userNode.value = new Date() | |
if (userNode === head && userNode === tail) { | |
return // we only update the login date | |
} | |
// we only care about maintaining order from the tail to the head | |
// so we have to move the userNode always to the top | |
if (userNode === tail) { | |
tail = tail.next; | |
tail.prev = null; | |
} else { | |
userNode.prev.next = userNode.next | |
userNode.next.prev = userNode.prev | |
} | |
} else { | |
userNode = new node(userId, new Date()) | |
users[userId] = userNode | |
if (head === null) { | |
head = userNode | |
tail = userNode | |
} | |
} | |
// always add the user to the top/head | |
userNode.next = null | |
userNode.prev = head; | |
head.next = userNode; | |
head = userNode | |
} | |
function retrieveUsersByLastLogin(days = 10) { | |
if (!tail) return [] | |
let tailNode = tail | |
const result = [] | |
const today = new Date() | |
// now we know that by traversing the list from the tail | |
// we will get an ordered list of dates in ascendent mode | |
while (tailNode !== null && daysDiff(tailNode.value, today) >= days) { | |
result.push(tailNode.key) | |
tailNode = tailNode.next | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yep that's the implementation. What i will improve is to extract the double linked list to a class and create a method to delete node from a reference.