Created
June 24, 2021 23:14
-
-
Save msroot/e052f2a86f063847f76154c47cd100ee to your computer and use it in GitHub Desktop.
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
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