Data Structure For Quizzes

mail@pastecode.io avatar
unknown
javascript
a month ago
1.6 kB
4
Indexable
Never
let users = []
let quizzes = {}

function addUsers(name, age) {
    if (!name) {
        return {error: "Name cannot be empty"};
    }
    if (age < 0) {
        return {error: "Provide a valid age"};
    }
    users.push({
        userId : users.length + 1,
        age: age,
        name: name
    });
}

function addQuiz(userId, title, description) {
    if (!title) {
        return {error: "Provide a valid title"};
    }
    if (!description) {
        return {error: "Provide a valid description"};
    }

    let uIndex = users.findIndex(user => user.userId == userId)
    if (uIndex === -1 ) {
        return {error: "User is not a valid user"};
    }

    if (!quizzes[userId]) {
        quizzes[userId] = []
    }
    quizzes[userId].push({
        id: quizzes[userId].length + 1,
        title: title,
        description: description
    })
}

function searchQuiz(userId, searchWord) {
    if (!searchWord) {
        return {error: "Provide a valid searchWord"};
    }

    let uIndex = users.findIndex(user => user.userId == userId)
    if (uIndex === -1 ) {
        return {error: "User is not a valid user"};
    }
    let qs = quizzes[userId]
    let filteredEntries = qs.filter(entry => {
        return entry.title.toLowerCase().includes(searchWord.toLowerCase()) ||
               entry.description.toLowerCase().includes(searchWord.toLowerCase());
    });
    
    return filteredEntries
}

addUsers("Rabbi", 2)
addQuiz(1, "Math", "For class 1")

addUsers("Momota", 2)
addQuiz(2, "Math", "For class 1")
addQuiz(2, "Eng", "For class 2")
console.log(searchQuiz(2, "1"))
Leave a Comment