|
| 1 | +class AssociationAlgorithm { |
| 2 | + constructor (requiredPercentageForAsssociation = 10) { |
| 3 | + this.REQUIRED_PERCENTAGE_FOR_ASSOCIATION = requiredPercentageForAsssociation |
| 4 | + |
| 5 | + this.associations = {} |
| 6 | + this.searches = {} |
| 7 | + } |
| 8 | + |
| 9 | + #associate (id, query) { |
| 10 | + if (!this.associations[id]) { this.associations[id] = [] } |
| 11 | + |
| 12 | + this.associations[id].push(query) |
| 13 | + } |
| 14 | + |
| 15 | + #search (id, query) { |
| 16 | + if (!this.searches[id]) { this.searches[id] = [] } |
| 17 | + |
| 18 | + let search = Number(this.searches[id][query]) |
| 19 | + |
| 20 | + if (!search) search = 0 |
| 21 | + |
| 22 | + this.searches[id][query] = search + 1 |
| 23 | + } |
| 24 | + |
| 25 | + // Main function to run the algorithm |
| 26 | + search (data) { |
| 27 | + const { id, views } = data.video |
| 28 | + const { query } = data.search |
| 29 | + |
| 30 | + if (!this.associations[id]) this.associations[id] = [] |
| 31 | + |
| 32 | + this.#search(id, query) |
| 33 | + |
| 34 | + const percentageOfViewsFromSearch = (Number(this.searches[id][query]) / Number(views)) * 100 |
| 35 | + |
| 36 | + if (percentageOfViewsFromSearch > this.REQUIRED_PERCENTAGE_FOR_ASSOCIATION) { |
| 37 | + // Associate the video with the search query |
| 38 | + |
| 39 | + this.#associate(id, query) |
| 40 | + } else { |
| 41 | + // The video does not have a high enough percentage of views from the query to be associated with it |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + isVideoAssociated (id, query) { |
| 46 | + return this.associations[id] && this.associations[id].includes(query) |
| 47 | + } |
| 48 | + |
| 49 | + getAssociations (id) { |
| 50 | + return this.associations[id] |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +export default AssociationAlgorithm |
0 commit comments