-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
# Compression | ||
|
||
Compression is a technique to reduce the size of data. It is used to save space and time in data storage and transmission. | ||
|
||
Includes the following algorithms: | ||
|
||
- Run Length Encoding |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { assertEquals, describe, it } from "../deps.ts"; | ||
import { RLE } from "./rle.ts"; | ||
|
||
describe("rle", () => { | ||
it("should be able to compress a string", () => { | ||
assertEquals(RLE.encode("aaaabbbccd"), "4a3b2c1d"); | ||
}); | ||
|
||
it("should be able to decompress a string", () => { | ||
assertEquals(RLE.decode("4a3b2c1d"), "aaaabbbccd"); | ||
}); | ||
|
||
it("should be able to compress and decompress a string", () => { | ||
const original = "aaaabbbccd"; | ||
const encoded = RLE.encode(original); | ||
const decoded = RLE.decode(encoded); | ||
|
||
assertEquals(decoded, original); | ||
}); | ||
}); |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// run length encoding | ||
|
||
export class RLE { | ||
static encode(data: string): string { | ||
let result = ""; | ||
let count = 1; | ||
|
||
for (let i = 1; i < data.length; i++) { | ||
if (data[i] === data[i - 1]) { | ||
count++; | ||
} else { | ||
result += count + data[i - 1]; | ||
count = 1; | ||
} | ||
} | ||
result += count + data[data.length - 1]; | ||
|
||
return result; | ||
} | ||
|
||
static decode(data: string): string { | ||
let result = ""; | ||
let count = ""; | ||
|
||
for (let i = 0; i < data.length; i++) { | ||
if (/\d/.test(data[i])) { | ||
count += data[i]; | ||
} else { | ||
result += data[i].repeat(Number(count)); | ||
count = ""; | ||
} | ||
} | ||
|
||
return result; | ||
} | ||
} |