Skip to content

Instantly share code, notes, and snippets.

@karolk
Last active June 23, 2020 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karolk/15e22c3899cf5bb408ab21ce1393df99 to your computer and use it in GitHub Desktop.
Save karolk/15e22c3899cf5bb408ab21ce1393df99 to your computer and use it in GitHub Desktop.
Do 2 objects have the same keys - 2 ways
const haveSameKeys = (objA, objB) => {
const keysOfA = Object.keys(objA)
const keysOfB = Object.keys(objB)
return keysOfA.length === keysOfB.length &&
keysOfA.every(key => keysOfB.includes(key))
}
// limited to however many primes we have
const primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]
const product = (a, b) => a * b
const haveSameKeys = (objA, objB) => {
const keysOfA = Object.keys(objA)
const keysOfB = Object.keys(objB)
const allKeys = keysOfA.concat(keysOfB)
const primeLookup = allKeys.reduce((acc, key, index) => {
if (!(key in acc)) {
acc[key] = primes[index]
}
return acc;
}, {})
const productOfA = keysOfA.map(key => primeLookup[key]).reduce(product)
const productOfB = keysOfB.map(key => primeLookup[key]).reduce(product)
return productOfA === productOfB
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment