Last active
December 22, 2022 22:38
-
-
Save Rudxain/50ebe38690d5a299da8152a4977e6934 to your computer and use it in GitHub Desktop.
Calculate Hamming Distance of any JS types, even different types. Supports mismatched lengths
This file contains hidden or 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
'use strict' | |
/** | |
@param {number | bigint | Iterable} a | |
@param {number | bigint | Iterable} b | |
@license Unlicense | |
*/ | |
const Hamming_dist = (a, b) => { | |
const get_chars = x => { | |
const t = typeof x | |
return 'number' == t || 'bigint' == t | |
// this is a bug when sizes are different | |
? [...x.toString(2)].reverse().map(b => !!+b) | |
// to-do: replace by `Intl.Segmenter` | |
: [...x] | |
} | |
a = get_chars(a) | |
b = get_chars(b) | |
let d = 0 | |
for (let i = 0; i < Math.max(a.length, b.length); i++) | |
if (a[i] !== b[i]) d++ | |
return d | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment