Last active
September 3, 2024 11:13
-
-
Save wazeerc/0f84028175ea050ba6c6c07998b4b6b6 to your computer and use it in GitHub Desktop.
Algorithm used to generate a number of recommendations based on selected movies (used in my movie-recs project).
This file contains 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
/** | |
* @summary Generates recommendations based on selected items and custom criteria using a point-based system. | |
* @param allItems - An array of all available items. | |
* @param selectedItems - An array of selected items. | |
* @param criteria - An array of functions to calculate points based on different criteria. | |
* @param numberOfRecommendations - The number of recommendations to generate, defaults to 3. | |
* @returns An array of recommended items. | |
* @example | |
* const allItems = [1, 2, 3, 4, 5]; | |
* const selectedItems = [1, 2]; | |
* const criteria = [ | |
* (item, selectedItems) => (selectedItems.includes(item) ? -1 : 1), | |
* (item) => (item % 2 === 0 ? 1 : 0), | |
* ]; | |
* const recommendations = genRecommendations(allItems, selectedItems, criteria); | |
* console.log(recommendations); // [3, 5, 4] | |
*/ | |
export const genRecommendations = <T>( | |
allItems: T[], | |
selectedItems: T[], | |
criteria: Array<(item: T, selectedItems: T[]) => number>, | |
numberOfRecommendations: number = 3 | |
): T[] => { | |
const recommendations = new Map<T, number>(); | |
allItems.forEach((item) => { | |
if (selectedItems.includes(item)) return; | |
let points = 0; | |
criteria.forEach((criterion) => { | |
points += criterion(item, selectedItems); | |
}); | |
recommendations.set(item, points); | |
}); | |
const filteredRecommendations = Array.from(recommendations.entries()) | |
.sort((a, b) => b[1] - a[1]) | |
.slice(0, numberOfRecommendations) | |
.map(([item]) => item); | |
return filteredRecommendations; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment