Select Git revision
+page.svelte

Jonas Zohren authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
+page.svelte 4.93 KiB
<script lang="js">
import { range } from './range';
let numCacheEntries = 4;
let valuesQueued = '1,2,3,4,5,6,7,6,8,5,9';
let oldestEntry = 0;
$: lruMatrix = makeLruMatrix(numCacheEntries);
/** @type {string[]} */
$: cacheEntries = new Array(numCacheEntries);
/** @param size {number}
* @returns {number[][]}
*/
function makeLruMatrix(size) {
const matrix = new Array(size - 1);
for (let i = 0; i < size - 1; i++) {
const row = new Array(size).fill(null);
for (let j = i + 1; j < size; j++) {
row[j] = 1;
}
matrix[i] = row;
}
return matrix;
}
function handleAccessNextValueClick() {
const rawValues = valuesQueued.trim();
if (rawValues.length === 0) {
return;
}
const [valueToAccess, ...rest] = rawValues
.split(',')
.map((v) => v.trim())
.filter((v) => v.length !== 0);
accessEntry(valueToAccess);
valuesQueued = rest.join(',');
}
/** @param value {string} */
function accessEntry(value) {
if (!isEntryInCache(value)) {
const oldestIndex = findOldestEntryIndex();
cacheEntries[oldestIndex] = value;
}
markIndexAsNewest(cacheEntries.indexOf(value));
}
/** @param value {string} */
function isEntryInCache(value) {
return cacheEntries.some((ce) => ce === value);
}
function findOldestEntryIndex() {
for (let possibleIndex = 0; possibleIndex < numCacheEntries; possibleIndex++) {
let isNotOldestIndex = false;
// Check that every thing on top of us is 0 (they are younger):
for (let i = 0; i < possibleIndex; i++) {
if (lruMatrix[i][possibleIndex] !== 0) {
isNotOldestIndex = true;
break;
}
}
if (isNotOldestIndex) continue;
// Check that everything to the right of us is 1 (we are older):
for (let j = possibleIndex + 1; j < numCacheEntries; j++) {
if (lruMatrix[possibleIndex][j] !== 1) {