Skip to content

Commit 8767d0b

Browse files
committed
add yt video association algorithm
1 parent cbc669a commit 8767d0b

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

Search/YoutubeVideoAssociation.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import AssociationAlgorithm from '../YoutubeVideoAssociation'
2+
3+
describe('Youtube Video Association Algorithm', () => {
4+
const search = {
5+
video: {
6+
id: 'dQw4w9WgXcQ',
7+
views: '100'
8+
},
9+
search: {
10+
query: 'Rick Roll'
11+
}
12+
}
13+
14+
const algorithm = new AssociationAlgorithm(10)
15+
16+
test('The video should not be associated after one search', () => {
17+
algorithm.search(search)
18+
19+
expect(algorithm.isVideoAssociated('dQw4w9WgXcQ', 'Rick Roll')).toBe(false)
20+
})
21+
22+
test('The video should be associated after 11 searches', () => {
23+
for (let i = 0; i < 10; i++) algorithm.search(search)
24+
})
25+
})

0 commit comments

Comments
 (0)