| 1 |
const formatImageUrl = (image) => |
| 2 |
image?.includes('?q=80&w=1470') ? image : `${image}?q=80&w=1470`; |
| 3 |
|
| 4 |
const hashString = (s) => { |
| 5 |
let h = 0; |
| 6 |
for (let i = 0; i < s.length; i++) { |
| 7 |
h = (h * 31 + s.charCodeAt(i)) | 0; |
| 8 |
} |
| 9 |
return Math.abs(h); |
| 10 |
}; |
| 11 |
|
| 12 |
const seededShuffle = (arr, seed) => { |
| 13 |
const result = [...arr]; |
| 14 |
let h = hashString(String(seed)); |
| 15 |
for (let i = result.length - 1; i > 0; i--) { |
| 16 |
h = (h * 1103515245 + 12345) | 0; |
| 17 |
const j = Math.abs(h) % (i + 1); |
| 18 |
[result[i], result[j]] = [result[j], result[i]]; |
| 19 |
} |
| 20 |
return result; |
| 21 |
}; |
| 22 |
|
| 23 |
export const replacePatternImages = (content, images, seed) => { |
| 24 |
if (!images?.length) return content; |
| 25 |
const matches = |
| 26 |
content.match(/https:\/\/images\.unsplash\.com\/[^\s"]+/g) || []; |
| 27 |
const uniqueUrls = [...new Set(matches)]; |
| 28 |
const order = seededShuffle(images, seed); |
| 29 |
return uniqueUrls.reduce( |
| 30 |
(updated, url, i) => |
| 31 |
updated.replaceAll(url, formatImageUrl(order[i] || url)), |
| 32 |
content, |
| 33 |
); |
| 34 |
}; |
| 35 |
|