An open API service indexing awesome lists of open source software.

https://github.com/kelreel/huffman-javascript

Huffman encode/decode text
https://github.com/kelreel/huffman-javascript

huffman-algorithm huffman-coding huffman-compression-algorithm huffman-tree

Last synced: 28 days ago
JSON representation

Huffman encode/decode text

Awesome Lists containing this project

README

        



Huffman coding JS (TypeScript)

[//]: # (

)

[//]: # ( DEMO)

[//]: # (

)

Huffman code is a particular type of optimal prefix code that is commonly used for lossless data compression. This is the implementation of the algorithm on TypeScript.

## Installation

Clone this repository and install modules:

```bash
git clone https://github.com/kanitelk/huffman-javascript.git
cd huffman-javascript
npm install
npm run dev(or build)
```

![](assets/split.png)

## Usage

The algorithm implementation is in the file /src/index.ts

Let's encode and decode plain text!

```typescript
import { getCodesFromText, encode, decode } from './huffman';

/** ENCODING */
let text: string = 'abracadabra';
let encodedText: string = '';

let codes: Map = getCodesFromText(text); // Symbols codes
let encodedArray: Array = encode(text, codes); // Get array of encoded symbols

encodedText = encodedArray.join(''); // Encoded array to string. Equals 0101100...

/** DECODING */
text = decode(encodedArray, codes); // Equals 'abracadabra'

```

![](assets/split.png)

## APIs

#### Encode text
```typescript
encode(text: string, codes: Map): Array
```

#### Decode text
```typescript
decode(text: Array, codes: Map):string
```

#### Get symbols codes from text
```typescript
getCodesFromText(text: string): Map
```

#### Get symbols frequency
```typescript
getFrequency(text: string): Array
```

#### Get Huffman Tree from frequency array
```typescript
getTree(arr: Array)
```

#### Get relative frequency array
```typescript
getRelativeFrequency(arr: Array): Array
```

#### Get text entropy
```typescript
getEntropyOfText(text: string): number
```