Table of Contents
- Problem Statement
- Assumptions
-
Requirements
- Create Polls
- Manage Polls
- Vote in Polls
- View Poll Results
- Poll Data
-
Implementation Details
-
Functions/Methods
- Create Poll
- Update Poll
- Delete Poll
- Vote In Poll
- View Poll Results
-
Functions/Methods
-
Data Models
- Poll
- Vote
- Implementation Details
- CODE
Problem Statement
You are required to design and implement an online polling system. The system should allow users to create, manage, and participate in polls. Each poll consists of a question and multiple options for answers. Users can vote on polls and view the results.
Assumptions :
- We are usin a Class based implementation
- We are not using additional Database to store this information
- As not DB & server is involved, no REST API
- simple Low Level approch on Polling System
Requirements
Create Polls:
- Users should be able to create a new poll with a question and multiple answer options.
- Each poll must have a unique identifier, a question, a list of options, and a timestamp of creation.
Manage Polls:
- Users should be able to update the question or options of an existing poll.
- Users should be able to delete a poll.
Vote in Polls:
- Users should be able to cast a vote for one of the options in a poll.
- Each user can only vote once per poll.
View Poll Results:
- Users should be able to view the current results of a poll, including the number of votes for each option.
Poll Data:
- Store polls, options, and votes in a way that allows efficient retrieval and updates.
- Ensure data integrity and consistency, especially when multiple users are voting simultaneously.
Implementation Details
Functions/Methods:
Create Poll
createPoll :
- Input: question (string), options (array of strings)
- Output: pollId (string), message (string)
- Example: createPoll("What is your favorite color?", ["Red", "Blue", "Green", "Yellow"]) returns {"pollId": "123", "message": "Poll created successfully."}
Update Poll
updatePoll :
- Input: pollId (string), question (string), options (array of strings)
- Output: message (string)
- Example: updatePoll("123", "Updated question?", ["Option1", "Option2"]) returns {"message": "Poll updated successfully."}
Delete Poll
deletePoll :
- Input: pollId (string)
- Output: message (string)
- Example: deletePoll("123") returns {"message": "Poll deleted successfully."}
Vote In Poll
voteInPoll :
- Input: pollId (string), userId (string), option (string)
- Output: message (string)
- Example: voteInPoll("123", "user1", "Option1") returns {"message": "Vote cast successfully."}
View Poll Results
viewPollResults :
- Input: pollId (string)
- Output: pollId (string), question (string), results (object with option keys and vote count values)
- Example: viewPollResults("123") returns {"pollId": "123", "question": "What is your favorite color?", "results": {"Red": 10, "Blue": 5, "Green": 3, "Yellow": 2}}
Data Models
- Poll:
{ "pollId": "123", "question": "What is your favorite color?", "options": ["Red", "Blue", "Green", "Yellow"], "createdAt": "2024-07-11T00:00:00Z" }
- Vote:
{ "pollId": "123", "userId": "user1", "option": "Red", "timestamp": "2024-07-11T01:00:00Z" }
Implementation Details
This code defines a basic polling system using JavaScript classes. It allows the creation, management, and voting in polls. Let's break down each part of the code:
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
systemdesignwithzeeshanali
Git: https://github.com/ZeeshanAli-0704/SystemDesignWithZeeshanAli
The above is the detailed content of Low-Level Design: Polling System. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

This article discusses how to use jQuery to obtain and set the inner margin and margin values of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Chinese version
Chinese version, very easy to use

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools
