Skip to content

Instantly share code, notes, and snippets.

@Rudxain
Last active December 22, 2022 22:38
Show Gist options
  • Save Rudxain/50ebe38690d5a299da8152a4977e6934 to your computer and use it in GitHub Desktop.
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
'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