Created
July 13, 2021 12:45
-
-
Save JSuder-xx/44fb9a9442275c8e300dbb5579566d90 to your computer and use it in GitHub Desktop.
Ramdajs Huffman 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
/** | |
* By using the RamdaJS library, the entire huffman encoding algorithm is represented with | |
* - const | |
* - Function application | |
* - Function creation (only 4 function closures created, mostly point-free) | |
* - Constructing and destructuring of both JSON objects and arrays | |
* | |
* Thought experiment to verify that a small subset of JavaScript is sufficient to produce sophisticated programs. | |
* Observe no use of if/switch/ternary/for/while, no dot field access, no infix binary operators. | |
*/ | |
const ReadMe = {} | |
const readCount = prop('count') | |
const mergeTwoNodes = ([left, right]) => [{ count: add(readCount(left), readCount(right)), left, right }] | |
const mergeToSingleNode = ifElse( | |
pipe(length, lt(__, 2)), | |
head, | |
pipe( | |
sortBy(readCount), | |
converge(concat, [pipe(take(2), mergeTwoNodes), drop(2)]), | |
(nodes) => mergeToSingleNode(nodes) | |
) | |
) | |
const huffmanTreeForString = pipe( | |
countBy(identity), | |
toPairs, | |
map(([char, count]) => ({char, count})), | |
mergeToSingleNode | |
) | |
const codePairsFromHuffmanTree = curry((pathThusFar, {char, left, right}) => | |
ifElse( | |
isNil, | |
() => concat( | |
codePairsFromHuffmanTree(concat(pathThusFar, '0'), left), | |
codePairsFromHuffmanTree(concat(pathThusFar, '1'), right), | |
), | |
() => [[char, pathThusFar]] | |
)(char) | |
) | |
const huffmanCodeFnFromString = pipe( | |
huffmanTreeForString, | |
codePairsFromHuffmanTree(''), | |
fromPairs, | |
flip(prop) | |
) | |
const huffmanEncodeString = pipe(converge(map, [huffmanCodeFnFromString, split('')]), join("")) | |
huffmanEncodeString('Hello!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment