Skip to content

Commit 9329875

Browse files
committed
blog:fix related weight calculator
1 parent b1c8d28 commit 9329875

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

src/theme/BlogPostPage/index.js

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,14 @@ function getMultipleRandomPosts(relatedPosts, number) {
1616
const weightedItems = [...relatedPosts];
1717
const result = [];
1818

19-
if (weightedItems.length > 15) {
20-
weightedItems.forEach((item) => {
21-
//square the weight to increase the chance of the post being selected
22-
item.relatedWeight = Math.pow(item.relatedWeight, 2);
23-
});
24-
}
19+
weightedItems.forEach((item) => {
20+
//square the weight to increase the chance of the post being selected
21+
//add a new field to avoid modify the original object
22+
item.sortWeight = weightedItems.length > 15 ? Math.pow(item.relatedWeight, 2) : item.relatedWeight;
23+
});
2524

2625
// Calculate the total weight
27-
let totalWeight = weightedItems.reduce((sum, item) => sum + item.relatedWeight, 0);
26+
let totalWeight = weightedItems.reduce((sum, item) => sum + item.sortWeight, 0);
2827

2928
while (weightedItems.length > 0) {
3029
// Generate a random value between 0 and the total weight
@@ -34,7 +33,7 @@ function getMultipleRandomPosts(relatedPosts, number) {
3433

3534
// Find the item that corresponds to the random value
3635
for (let i = 0; i < weightedItems.length; i++) {
37-
weightSum += weightedItems[i].relatedWeight;
36+
weightSum += weightedItems[i].sortWeight;
3837
if (randomValue <= weightSum) {
3938
selectedIndex = i;
4039
break;
@@ -45,7 +44,7 @@ function getMultipleRandomPosts(relatedPosts, number) {
4544
if (selectedIndex !== -1) {
4645
const [selectedItem] = weightedItems.splice(selectedIndex, 1);
4746
result.push(selectedItem);
48-
totalWeight -= selectedItem.relatedWeight;
47+
totalWeight -= selectedItem.sortWeight;
4948
}
5049
}
5150

0 commit comments

Comments
 (0)