Created
July 14, 2021 12:56
-
-
Save SparK-Cruz/d3a6dd8cb47b57c8536de6cae358b810 to your computer and use it in GitHub Desktop.
Most Visited Sequence
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 SEPARATOR = ':::'; | |
module.exports = (function() { | |
const cls = function() { | |
this.userVisits = {}; | |
}; | |
const parseSequences = function(userVisits, length) { | |
const sequences = {}; | |
const size = length - 1; | |
for (let i = 0; i < userVisits.length; i++) { | |
const visits = userVisits[i]; | |
const limit = visits.length - size; | |
for (let j = 0; j < limit; j++) { | |
const key = visits.slice(j, j + size).join(SEPARATOR); | |
if (typeof sequences[key] === 'undefined') | |
sequences[key] = 0; | |
sequences[key]++; | |
} | |
} | |
return sequences; | |
} | |
cls.prototype.visit = function(user, page) { | |
const key = 'user' + user; | |
this.userVisits[key] ||= []; | |
this.userVisits[key].push(page); | |
}; | |
cls.prototype.getMostVisitedSequence = function(length) { | |
const sequences = parseSequences(this.userVisits, length); | |
const largest = {key: '', value: 0}; | |
for(let key in sequences) { | |
if (sequences[key] <= largest.value) | |
continue; | |
largest.key = key; | |
largest.value = sequences[key]; | |
} | |
return largest.key.split(SEPARATOR); | |
}; | |
return cls; | |
})(); |
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 Subject = require('./index.js'); | |
function testSequence1() { | |
const subject = new Subject(); | |
// adicionar visitas | |
subject.visit(1, 'A'); | |
subject.visit(2, 'B'); | |
subject.visit(1, 'C'); | |
subject.visit(2, 'A'); | |
subject.visit(2, 'C'); | |
subject.visit(1, 'D'); | |
subject.visit(2, 'D'); | |
// testar resultado | |
console.log(assertSequence(subject.getMostVisitedSequence(3), ['A', 'C', 'D']) ? '.' : 'F'); | |
} | |
function assertSequence(sequence, assertion) { | |
if (sequence.length !== assertion.length) | |
return false; | |
for (let i = 0; i < sequence.length; i++) { | |
if (sequence[i] !== assertion[i]) | |
return false; | |
} | |
return true; | |
} | |
testSequence1(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The for loop in line :12 wouldn't work because userVisits is an object. I'd have to either iterate through its value by using
Object.values(userVisits)
or by using the for..in construct.