Last active
May 10, 2023 01:08
-
-
Save 1forh/8d32ec6bc8ebf3fb6046b172b57b46cc to your computer and use it in GitHub Desktop.
Algorand NFT - Rarity Scores
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 rarityScore = getTraitRarityScore(nft, allNfts); | |
// https://medium.com/@nfthelperbot/understanding-nft-rarity-calculation-c724518efd63 | |
// rarityScore = 1 ÷ ([Number of Items With That Trait Value] / [Total Number of Items in Collection]) | |
function getTraitRarityScore(nft, allNfts) { | |
if (!nft?.metadata?.properties || Object.keys(nft.metadata.properties).length === 0) return 0; | |
const total = allNfts.length; | |
const traitFrequencies = getTraitFrequencies(allNfts); | |
const rarityScore = Object.entries(nft.metadata.properties).reduce((acc, [trait, value]) => { | |
const traitFrequency = traitFrequencies[`${trait}:${value}`]; | |
const rarity = 1 / (traitFrequency / total); | |
return acc + rarity; | |
}, 0); | |
return rarityScore; | |
} | |
function getTraitFrequencies(allNfts) { | |
const formattedNfts = allNfts.map((nft) => { | |
if (!nft.metadata?.properties) { | |
return {}; | |
} | |
return { | |
...nft.metadata?.properties, | |
}; | |
}); | |
const traitFrequencies = {}; | |
formattedNfts.forEach((nft) => { | |
Object.entries(nft).forEach(([trait, value]) => { | |
traitFrequencies[`${trait}:${value}`] = (traitFrequencies[`${trait}:${value}`] || 0) + 1; | |
}); | |
}); | |
return traitFrequencies; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment