Skip to content

Instantly share code, notes, and snippets.

@msroot
Created June 24, 2021 23:14
Show Gist options
  • Save msroot/e052f2a86f063847f76154c47cd100ee to your computer and use it in GitHub Desktop.
Save msroot/e052f2a86f063847f76154c47cd100ee to your computer and use it in GitHub Desktop.
const generateHash = require('object-hash')
const randomColor = require('randomcolor')
const similarity = {}
const uniqRandomColor = (options = {}) => {
let color = randomColor(options)
while (Object.values(similarity).includes(color)) {
color = randomColor(options)
}
return color
}
const objectSimilarity = (objects = [], options = {}) => {
return objects.map((object) => {
const hash = generateHash(object)
const color = similarity[hash]
? similarity[hash]
: (similarity[hash] = uniqRandomColor(options))
return { object, color, hash }
})
}
export { objectSimilarity }
describe('uniqRandomColor', () => {
it('similarity', () => {
const data = objectSimilarity([{ foo: 1 }, { foo: 1 }, { bar: 1 }])
const colors = {}
data.map((e) => {
colors[e.hash] ||= []
colors[e.hash].push(e.color)
})
Object.entries(colors).map(([hash, colors]) => {
const uniq = [...new Set(colors)]
expect(uniq.length).to.be.equal(1)
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment