-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileSystem.js
108 lines (92 loc) · 2.84 KB
/
fileSystem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
class Superblock {
constructor(totalBlocks, blockSize) {
this.totalBlocks = totalBlocks;
this.blockSize = blockSize;
this.freeBlockList = Array.from({ length: totalBlocks }, (_, index) => index);
}
allocateBlock() {
if (this.freeBlockList.length > 0) {
return this.freeBlockList.pop();
} else {
throw new Error('No free blocks available.');
}
}
deallocateBlock(blockNumber) {
this.freeBlockList.push(blockNumber);
}
}
class Inode {
constructor(permissions) {
this.permissions = permissions;
this.size = 0;
this.dataBlocks = [];
}
addDataBlock(blockNumber) {
this.dataBlocks.push(blockNumber);
}
removeDataBlock(blockNumber) {
const index = this.dataBlocks.indexOf(blockNumber);
if (index !== -1) {
this.dataBlocks.splice(index, 1);
}
}
}
class FileSystem {
constructor(totalBlocks, blockSize) {
this.superblock = new Superblock(totalBlocks, blockSize);
this.inodes = {};
this.dataBlocks = Array.from({ length: totalBlocks }, () => '');
}
createFile(permissions) {
const inode = new Inode(permissions);
const inodeIndex = Object.keys(this.inodes).length + 1;
this.inodes[inodeIndex] = inode;
return inodeIndex;
}
writeToFile(fileId, content) {
if (this.inodes[fileId]) {
const inode = this.inodes[fileId];
const blockNumber = this.superblock.allocateBlock();
this.dataBlocks[blockNumber] = content;
inode.addDataBlock(blockNumber);
inode.size += content.length;
} else {
throw new Error('File not found.');
}
}
readFromFile(fileId) {
if (this.inodes[fileId]) {
const inode = this.inodes[fileId];
let content = '';
for (const blockNumber of inode.dataBlocks) {
content += this.dataBlocks[blockNumber];
}
return content;
} else {
throw new Error('File not found.');
}
}
deleteFile(fileId) {
if (this.inodes[fileId]) {
const inode = this.inodes[fileId];
for (const blockNumber of inode.dataBlocks) {
this.superblock.deallocateBlock(blockNumber);
this.dataBlocks[blockNumber] = '';
}
delete this.inodes[fileId];
} else {
throw new Error('File not found.');
}
}
}
// Create a file system with 100 blocks of size 4096 bytes each
const fileSystem = new FileSystem(100, 4096);
// Create a file
const fileId = fileSystem.createFile('rw-r--r--');
// Write to the file
fileSystem.writeToFile(fileId, 'Hello, World!\nThis is a test file.\n');
// Read from the file
const content = fileSystem.readFromFile(fileId);
console.log(content);
// Delete the file
fileSystem.deleteFile(fileId);