搜尋
首頁web前端js教程底層設計:輪詢系統

Low-Level Design: Polling System

目錄

  1. 問題陳述
  2. 假設
  3. 要求
    • 建立民意調查
    • 管理投票
    • 參與投票
    • 查看投票結果
    • 民調數據
  4. 實施細節
    • 函數/方法
      • 創建投票
      • 更新民調
      • 刪除投票
      • 參與投票
      • 查看投票結果
  5. 資料模型
    • 投票
    • 投票
  6. 實作細節
  7. 代碼

問題陳述

您需要設計並實現一個線上投票系統。系統應允許使用者建立、管理和參與民意調查。每個民意調查都包含一個問題和多個答案選項。用戶可以對民意調查進行投票並查看結果。

假設:

  • 我們正在使用基於類別的實作
  • 我們沒有使用額外的資料庫來儲存此資訊
  • 由於不涉及資料庫和伺服器,因此沒有REST API
  • 投票系統的簡單低階方法

要求

創建投票:

  • 使用者應該能夠建立一個包含問題和多個答案選項的新民意調查。
  • 每個民調必須有唯一的識別碼、問題、選項清單和建立時間戳記。

管理民意調查:

  • 使用者應該能夠更新現有民意調查的問題或選項。
  • 使用者應該能夠刪除投票。

投票:

  • 使用者應該能夠對民意調查中的其中一個選項進行投票。
  • 每位使用者每次投票只能投票一次。

查看投票結果:

  • 使用者應該能夠查看目前的投票結果,包括每個選項的得票數。

民意調查數據:

  • 以允許高效檢索和更新的方式儲存民意調查、選項和投票。
  • 確保資料完整性和一致性,尤其是當多個使用者同時投票時。

實施細節

功能/方法:

創建投票

createPoll :

  • 輸入:問題(字串),選項(字串陣列)
  • 輸出:pollId(字串),訊息(字串)
  • 範例:createPoll("你最喜歡的顏色是什麼?", ["Red", "Blue", "Green", "Yellow"]) 回傳{"pollId": "123", " message" :"投票創建成功。

更新投票

更新投票 :

  • 輸入:pollId(字串),問題(字串),選項(字串陣列)
  • 輸出:訊息(字串)
  • 範例:updatePoll("123", "更新問題?", ["Option1", "Option2"]) 回傳 {"message": "投票更新成功。"}

刪除投票

刪除投票 :

  • 輸入:pollId(字串)
  • 輸出:訊息(字串)
  • 範例:deletePoll("123") 回傳 {"message": "投票已成功刪除。"}

投票

投票投票 :

  • 輸入:pollId(字串)、userId(字串)、選項(字串)
  • 輸出:訊息(字串)
  • 範例: voteInPoll("123", "user1", "Option1") 回傳 {"message": "投票成功。"}

查看投票結果

viewPollResults :

  • 輸入:pollId(字串)
  • 輸出:pollId(字串),問題(字串),結果(帶有選項鍵和投票計數值的物件)
  • 範例: viewPollResults("123") returns {"pollId": "123", "question": "你最喜歡的顏色是什麼?", "results": {"Red": 10, "Blue “:5,“綠色”:3,“黃色”:2}}

資料模型

  • 民調
{
  "pollId": "123",
  "question": "What is your favorite color?",
  "options": ["Red", "Blue", "Green", "Yellow"],
  "createdAt": "2024-07-11T00:00:00Z"
}
  • 投票
{
  "pollId": "123",
  "userId": "user1",
  "option": "Red",
  "timestamp": "2024-07-11T01:00:00Z"
}

實施細節

這段程式碼使用 JavaScript 類別定義了一個基本的輪詢系統。它允許創建、管理和投票。讓我們分解一下程式碼的各個部分:

1. Class Definitions

Poll Class

  • Purpose: Represents an individual poll.
  • Constructor Parameters:
    • id: A unique identifier for the poll.
    • question: The question being asked in the poll.
    • options: An array of possible options that users can vote on.
  • Properties:
    • pollId: Stores the unique ID of the poll.
    • question: Stores the poll question.
    • options: Stores the array of options.
    • createdAt: Stores the creation date and time of the poll.

Vote Class

  • Purpose: Represents an individual vote cast by a user.
  • Constructor Parameters:
    • pollId: The ID of the poll the vote is associated with.
    • userId: The ID of the user who cast the vote.
    • option: The option that the user voted for.
  • Properties:
    • pollId: Stores the poll ID for which the vote was cast.
    • userId: Stores the user ID of the voter.
    • option: Stores the option that the user voted for.
    • timestamp: Stores the date and time when the vote was cast.

2. PollManager Class

Purpose: Manages the entire polling system, including creating polls, managing votes, and viewing results.

Constructor:

  • Properties:
    • polls: A Map that stores all polls, where the key is the poll ID and the value is the Poll object.
    • pollResults: A Map that stores the results of each poll, where the key is the poll ID and the value is another Map that tracks votes for each option.
    • userVotes: A Map that stores the votes by each user, where the key is the poll ID and the value is another Map that tracks whether a user has voted in that poll.

Methods:

  • createPoll(question, options)

    • Generates a new poll with a unique ID.
    • Initializes the poll results, setting the vote count for each option to 0.
    • Stores the poll and returns the generated poll ID.
  • updatePoll(pollId, question, options)

    • Updates the question and options for an existing poll.
    • Resets the poll results to 0 for the updated options.
    • Returns a success message if the poll is found, otherwise returns "Poll not found."
  • deletePoll(pollId)

    • Deletes a poll by its ID.
    • Also removes associated poll results and user votes.
    • Returns a success message if the poll is found, otherwise returns "Poll not found."
  • voteInPoll(pollId, userId, option)

    • Allows a user to cast a vote in a specific poll.
    • Ensures a user can only vote once per poll.
    • Updates the vote count for the selected option if valid.
    • Returns appropriate messages depending on whether the vote was successful, the user had already voted, or the poll or option was invalid.
  • viewPollResults(pollId)

    • Returns the results of a specific poll in an array format, where each entry is a tuple of the option and its vote count.
    • Returns "Poll not found" if the poll doesn't exist.

3. Example Usage

  • Poll Creation: A poll is created asking, "What is your favorite color?" with options ["Red", "Blue", "Green", "Yellow"]. The poll ID is generated as "1".
  • Voting: Multiple users vote in the poll, and the system ensures users can only vote once.
  • Viewing Results: The poll results are displayed, showing the vote counts for each option.
  • Updating the Poll: The poll's question and options are updated, resetting the results.
  • Voting in Updated Poll: A user votes in the updated poll, and the results are displayed.
  • Poll Deletion: The poll is deleted, and an attempt to view the results afterward confirms the poll no longer exists.

This implementation provides a basic but functional polling system, handling common scenarios such as poll creation, updating, voting, and deletion.

CODE

class Poll {
    constructor(id, question, options) {
        this.pollId = id;
        this.question = question;
        this.options = options;
        this.createdAt = new Date();
    }
}

class Vote {
    constructor(pollId, userId, option) {
        this.pollId = pollId;
        this.userId = userId;
        this.option = option;
        this.timestamp = new Date();
    }
}

class PollManager {
    constructor() {
        this.polls = new Map();
        this.pollResults = new Map();
        this.userVotes = new Map();
    }

    createPoll(question, options) {
        const pollId = (this.polls.size + 1).toString();
        const poll = new Poll(pollId, question, options);
        this.polls.set(pollId, poll);

        const result = new Map();
        options.forEach(option => result.set(option, 0));
        this.pollResults.set(pollId, result);

        return pollId;
    }

    updatePoll(pollId, question, options) {
        const poll = this.polls.get(pollId);
        if (poll) {
            poll.question = question;
            poll.options = options;

            // Update results for the new options
            const result = new Map();
            options.forEach(option => result.set(option, 0));
            this.pollResults.set(pollId, result);

            return "Poll updated successfully.";
        }
        return "Poll not found.";
    }

    deletePoll(pollId) {
        if (this.polls.delete(pollId)) {
            this.pollResults.delete(pollId);
            this.userVotes.delete(pollId);
            return "Poll deleted successfully.";
        }
        return "Poll not found.";
    }

    voteInPoll(pollId, userId, option) {
        const poll = this.polls.get(pollId);
        if (poll) {
            if (!this.userVotes.has(pollId)) {
                this.userVotes.set(pollId, new Map());
            }

            const userVote = this.userVotes.get(pollId);
            if (userVote.get(userId)) {
                return "User has already voted.";
            }

            const result = this.pollResults.get(pollId);
            if (result.has(option)) {
                result.set(option, result.get(option) + 1);
                userVote.set(userId, true);
                return "Vote cast successfully.";
            } else {
                return "Invalid option.";
            }
        }
        return "Poll not found.";
    }

    viewPollResults(pollId) {
        const results = this.pollResults.get(pollId);
        if (results) {
            return Array.from(results.entries());
        }
        return "Poll not found.";
    }
}

// Example usage
const pollManager = new PollManager();

// Creating a poll
const pollId = pollManager.createPoll("What is your favorite color?", ["Red", "Blue", "Green", "Yellow"]);
console.log("Poll created with ID:", pollId);

// Voting in the poll
let voteMessage = pollManager.voteInPoll(pollId, "user1", "Red");
console.log(voteMessage);

voteMessage = pollManager.voteInPoll(pollId, "user2", "Blue");
console.log(voteMessage);

voteMessage = pollManager.voteInPoll(pollId, "user1", "Green");
console.log(voteMessage); // Should inform the user has already voted

// Viewing poll results
let results = pollManager.viewPollResults(pollId);
console.log("Poll results for poll ID", pollId, ":", results);

// Updating the poll
let updateMessage = pollManager.updatePoll(pollId, "What is your favorite primary color?", ["Red", "Blue", "Yellow"]);
console.log(updateMessage);

// Voting in the updated poll
voteMessage = pollManager.voteInPoll(pollId, "user3", "Yellow");
console.log(voteMessage);

// Viewing updated poll results
results = pollManager.viewPollResults(pollId);
console.log("Updated poll results for poll ID", pollId, ":", results);

// Deleting the poll
let deleteMessage = pollManager.deletePoll(pollId);
console.log(deleteMessage);

// Attempting to view results of a deleted poll
results = pollManager.viewPollResults(pollId);
if (typeof results === "string") {
    console.log(results);
}


// Response
// Poll created with ID: 1
// Vote cast successfully.
// Vote cast successfully.
// User has already voted.
// Poll results for poll ID 1 : [['Red', 1], ['Blue', 1], ['Green', 0], ['Yellow', 0]]
// Poll updated successfully.
// Vote cast successfully.
// Updated poll results for poll ID 1 : [['Red', 0], ['Blue', 0], ['Yellow', 1]]
// Poll deleted successfully.
// Poll not found.

Note: Please follow for more detail & Enchanced version of this article with DB, API & other system Design Concept.

More Details:

Get all articles related to system design
Hastag: SystemDesignWithZeeshanAli

系統設計與zeeshanali

Git:https://github.com/ZeeshanAli-0704/SystemDesignWithZeeshanAli

以上是底層設計:輪詢系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在JavaScript中替換字符串字符在JavaScript中替換字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

自定義Google搜索API設置教程自定義Google搜索API設置教程Mar 04, 2025 am 01:06 AM

本教程向您展示瞭如何將自定義的Google搜索API集成到您的博客或網站中,提供了比標準WordPress主題搜索功能更精緻的搜索體驗。 令人驚訝的是簡單!您將能夠將搜索限制為Y

示例顏色json文件示例顏色json文件Mar 03, 2025 am 12:35 AM

本文系列在2017年中期進行了最新信息和新示例。 在此JSON示例中,我們將研究如何使用JSON格式將簡單值存儲在文件中。 使用鍵值對符號,我們可以存儲任何類型的

10個jQuery語法熒光筆10個jQuery語法熒光筆Mar 02, 2025 am 12:32 AM

增強您的代碼演示文稿:10個語法熒光筆針對開發人員在您的網站或博客上共享代碼段的開發人員是開發人員的常見實踐。 選擇合適的語法熒光筆可以顯著提高可讀性和視覺吸引力。 t

構建您自己的Ajax Web應用程序構建您自己的Ajax Web應用程序Mar 09, 2025 am 12:11 AM

因此,在這裡,您準備好了解所有稱為Ajax的東西。但是,到底是什麼? AJAX一詞是指用於創建動態,交互式Web內容的一系列寬鬆的技術。 Ajax一詞,最初由Jesse J創造

8令人驚嘆的jQuery頁面佈局插件8令人驚嘆的jQuery頁面佈局插件Mar 06, 2025 am 12:48 AM

利用輕鬆的網頁佈局:8 ESTISSEL插件jQuery大大簡化了網頁佈局。 本文重點介紹了簡化該過程的八個功能強大的JQuery插件,對於手動網站創建特別有用

10 JavaScript和JQuery MVC教程10 JavaScript和JQuery MVC教程Mar 02, 2025 am 01:16 AM

本文介紹了關於JavaScript和JQuery模型視圖控制器(MVC)框架的10多個教程的精選選擇,非常適合在新的一年中提高您的網絡開發技能。 這些教程涵蓋了來自Foundatio的一系列主題

什麼是這個'在JavaScript?什麼是這個'在JavaScript?Mar 04, 2025 am 01:15 AM

核心要點 JavaScript 中的 this 通常指代“擁有”該方法的對象,但具體取決於函數的調用方式。 沒有當前對象時,this 指代全局對象。在 Web 瀏覽器中,它由 window 表示。 調用函數時,this 保持全局對象;但調用對象構造函數或其任何方法時,this 指代對象的實例。 可以使用 call()、apply() 和 bind() 等方法更改 this 的上下文。這些方法使用給定的 this 值和參數調用函數。 JavaScript 是一門優秀的編程語言。幾年前,這句話可

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具