Skip to content

Instantly share code, notes, and snippets.

@juliangroen
Last active August 2, 2020 03:24
Show Gist options
  • Save juliangroen/907409d288592aa368ae84d1640342cf to your computer and use it in GitHub Desktop.
Save juliangroen/907409d288592aa368ae84d1640342cf to your computer and use it in GitHub Desktop.
Simple example of memory paging using a FIFO algorithim.
// first frame
const a = [];
// second frame
const b = [];
// third frame
const c = [];
// queue to track oldest frame
const q = [];
// FIFO algorithm to access a page from command set and push it into a memory frame.
// if the page is already in memory it skips to the next page.
// oldest frame is used to house new frame not in memory.
const p = (num) => {
console.log(`accessing ${num}`);
// check if current frame is in memory
if (num === a[(a.length)-1] || num === b[(b.length)-1] || num === c[(c.length)-1]) {
console.log(`${num} is already in a frame`);
// if it's not in memory check if a frame is empty and push the page into it and add frame to oldest queue.
} else {
if (a.length === 0) {
a.push(num);
q.push('a');
console.log(`pushed ${num} into a`);
} else if (b.length === 0) {
b.push(num);
q.push('b');
console.log(`pushed ${num} into b`);
} else if (c.length === 0) {
c.push(num);
q.push('c');
console.log(`pushed ${num} into c`);
// if no frames are empty, push page into oldest frame and shift that frame out of the queue.
} else {
let old = q.shift();
q.push(old);
// IIFE to exchange variable name to array reference
let arr = (()=>{
switch(old) {
case 'a':
return a;
break;
case 'b':
return b;
break;
case 'c':
return c;
break;
}
})();
arr.push(num);
console.log(`pushed ${num} into ${old}`);
}
}
};
// set of pages waiting to be accessed by memory
let set = [1, 2, 3, 4, 2, 3, 4, 1, 2, 1 , 1, 3, 1, 4];
// iterate through command set and access each using the FIFO algorithm
set.forEach(num => {
p(num);
})
// display ending state of the three frames
console.log(a);
console.log(b);
console.log(c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment