Last active
November 22, 2017 21:22
-
-
Save evaldosantos/985af6cf09d4d5032d36157e7e818012 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MMemory { | |
constructor(size, memoryAllocationStrategy) { | |
this._size = size; | |
this._blocks = []; | |
} | |
totalAllocatedBlocks() { | |
return this._blocks.reduce( (total, block) => total + block.getSize(), 0 ); | |
} | |
isFull() { | |
return this._size === this.totalAllocatedBlocks(); | |
} | |
getSize() { | |
return this._size; | |
} | |
allocate(block) { | |
if( this.isFull() ) { | |
console.log(1); | |
let bestFit = | |
this._blocks | |
.filter((currentBlock) => currentBlock.isFree()) | |
.sort((blockA, blockB) => blockA.getSize() > blockB.getSize() ? 1 : -1 ) | |
.find((currentBlock) => currentBlock.getSize() > block.getSize()); | |
console.log(bestFit); | |
} else if( block.getSize() <= this.dealocatedSpace() ) { | |
console.log(3); | |
this._blocks.push(block); | |
} else { | |
console.log(2); | |
throw "OutOfMemory"; | |
} | |
} | |
dealocate(blockId) { | |
this._blocks.forEach(function(block) { | |
if( block.getId() === blockId ) { | |
block.free(); | |
} | |
}); | |
} | |
dealocatedSpace() { | |
const spaceAllocatedByBlocks = | |
this._blocks | |
.reduce( (total, block) => total + block.getSize(), 0 ); | |
return this._size - spaceAllocatedByBlocks; | |
} | |
} | |
class BestFit { | |
static execute(memory, block) { | |
console.log(memory, block); | |
} | |
} | |
class BBlock { | |
constructor(size, status="used") { | |
this._size = size; | |
this._status = status; | |
this._id = ++BBlock.counter; | |
} | |
getId() { | |
return this._id; | |
} | |
getSize() { | |
return this._size; | |
} | |
getStatus() { | |
return this._status; | |
} | |
free() { | |
this._status = "free"; | |
} | |
isFree() { | |
return this._status === "free"; | |
} | |
isUsed() { | |
return this._status === "used"; | |
} | |
} | |
BBlock.counter = 0; | |
let m = new MMemory(1024, BestFit); | |
m.allocate(new BBlock(1, 'free')); | |
m.allocate(new BBlock(2, 'free')); | |
m.allocate(new BBlock(4, 'free')); | |
m.allocate(new BBlock(8, 'free')); | |
m.allocate(new BBlock(16, 'free')); | |
m.allocate(new BBlock(32, 'free')); | |
m.allocate(new BBlock(64, 'free')); | |
m.allocate(new BBlock(128, 'free')); | |
m.allocate(new BBlock(256, 'free')); | |
m.allocate(new BBlock(512, 'free')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment