@nftgo/gorarity
Version:
An algorithm to calculate rarity of NFT(how special it is), based on Jaccard Distance.
57 lines (56 loc) • 2.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RarityRanker = void 0;
const scoring_1 = require("./scoring");
const token_feature_extractor_1 = require("./scoring/token-feature-extractor");
class RarityRanker {
constructor() { }
/**
* @description Ranks tokens in the collection with the default scorer implementation.
* @param collection
* @param scorer
* @returns Array of TokenRarity objects with score, rank and token information sorted by rank.
*/
static rankCollection(collection, scorer = RarityRanker.defaultScorer) {
if (!collection || !collection.tokens || collection.tokens.length === 0)
return [];
const tokens = collection.tokens;
const scores = scorer.scoreTokens(collection, tokens);
if (scores.length !== tokens.length) {
throw new Error(`dimension of scores doesn't match dimension of tokens`);
}
const tokenRarities = [];
for (let idx = 0; idx < tokens.length; idx++) {
const tokenFeatures = token_feature_extractor_1.TokenFeatureExtractor.extractUniqueTraitCount(collection, tokens[idx]);
tokenRarities.push({
token: tokens[idx],
score: scores[idx],
tokenFeatures: tokenFeatures,
rank: 0, // Prefill
});
}
return RarityRanker.setRarityRanks(tokenRarities);
}
/**
* @description Set the ranking of token according to it's rarity socre.
* @param tokenRarities Unordered array of tokens with rarity score information
* @returns Ordered array of tokens sorted by score descending
*/
static setRarityRanks(tokenRarities) {
tokenRarities.sort((a, b) => b.score - a.score);
let rank = 0;
let preScore = -1;
let i = 0;
for (const tokenRarity of tokenRarities) {
if (tokenRarity.score !== preScore) {
rank = i + 1;
preScore = tokenRarity.score;
}
tokenRarity.rank = rank;
i++;
}
return tokenRarities;
}
}
exports.RarityRanker = RarityRanker;
RarityRanker.defaultScorer = new scoring_1.Scorer();