-
Notifications
You must be signed in to change notification settings - Fork 14
/
creative-rotation-worklet.js
83 lines (71 loc) · 2.55 KB
/
creative-rotation-worklet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class SelectURLOperation {
async run(urls, data) {
// Read the rotation mode from Shared Storage
const rotationMode = await sharedStorage.get('creative-rotation-mode');
// Generate a random number to be used for rotation
const randomNumber = Math.random();
let index;
switch (rotationMode) {
/**
* Sequential rotation
* - Rotates the creatives in order
* - Example: A -> B -> C -> A ...
*/
case 'sequential':
const currentIndex = await sharedStorage.get('creative-rotation-index');
index = parseInt(currentIndex, 10);
const nextIndex = (index + 1) % urls.length;
console.log(`index = ${index} / next index = ${nextIndex}`);
await sharedStorage.set('creative-rotation-index', nextIndex.toString());
break;
/**
* Evenly-distributed rotation
* - Rotates the creatives with equal probability
* - Example: A=33% / B=33% / C=33%
*/
case 'even-distribution':
index = Math.floor(randomNumber * urls.length);
break;
/**
* Weighted rotation
* - Rotates the creatives with weighted probability
* - Example: A=70% / B=20% / C=10%
*/
case 'weighted-distribution':
console.log('data = ', JSON.stringify(data));
// Find the first URL where the cumnulative sum of the weights
// exceed the random number. The array is sorted by the weight
// in descending order.
let weightSum = 0;
const { url } = data
.sort((a, b) => b.weight - a.weight)
.find(({ weight }) => {
weightSum += weight;
return weightSum > randomNumber;
});
index = urls.indexOf(url);
break;
default:
index = 0;
}
console.log(JSON.stringify({ index, randomNumber, rotationMode }));
return index;
}
}
// Register the operation as 'creative-rotation'
register('creative-rotation', SelectURLOperation);