Skip to content

Commit

Permalink
feat: compression
Browse files Browse the repository at this point in the history
  • Loading branch information
fdemir committed Apr 12, 2024
1 parent c56c37c commit 1053983
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/compression/README.md
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
20 changes: 20 additions & 0 deletions src/compression/rle.test.ts
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);
});
});
36 changes: 36 additions & 0 deletions src/compression/rle.ts
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;
}
}

0 comments on commit 1053983

Please sign in to comment.