Skip to content

Instantly share code, notes, and snippets.

@JSuder-xx
Created July 13, 2021 12:45
Show Gist options
  • Save JSuder-xx/44fb9a9442275c8e300dbb5579566d90 to your computer and use it in GitHub Desktop.
Save JSuder-xx/44fb9a9442275c8e300dbb5579566d90 to your computer and use it in GitHub Desktop.
Ramdajs Huffman encoding
/**
* 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