Heim > Web-Frontend > js-Tutorial > Hauptteil

Low-Level-Design: Umfragesystem

WBOY
Freigeben: 2024-08-30 18:39:31
Original
695 Leute haben es durchsucht

Low-Level Design: Polling System

Inhaltsverzeichnis

  1. Problembeschreibung
  2. Annahmen
  3. Anforderungen
    • Umfragen erstellen
    • Umfragen verwalten
    • Stimmen Sie in Umfragen ab
    • Umfrageergebnisse anzeigen
    • Umfragedaten
  4. Implementierungsdetails
    • Funktionen/Methoden
      • Umfrage erstellen
      • Umfrage aktualisieren
      • Umfrage löschen
      • Stimmen Sie in der Umfrage ab
      • Umfrageergebnisse anzeigen
  5. Datenmodelle
    • Umfrage
    • Abstimmen
  6. Implementierungsdetails
  7. CODE

Problemstellung

Sie müssen ein Online-Umfragesystem entwerfen und implementieren. Das System sollte es Benutzern ermöglichen, Umfragen zu erstellen, zu verwalten und daran teilzunehmen. Jede Umfrage besteht aus einer Frage und mehreren Antwortmöglichkeiten. Benutzer können an Umfragen teilnehmen und die Ergebnisse anzeigen.

Annahmen:

  • Wir verwenden eine klassenbasierte Implementierung
  • Wir verwenden keine zusätzliche Datenbank, um diese Informationen zu speichern
  • Da keine Datenbank und kein Server beteiligt sind, gibt es auch keine REST-API
  • einfacher Low-Level-Ansatz für das Polling-System

Anforderungen

Umfragen erstellen:

  • Benutzer sollten in der Lage sein, eine neue Umfrage mit einer Frage und mehreren Antwortoptionen zu erstellen.
  • Jede Umfrage muss eine eindeutige Kennung, eine Frage, eine Liste von Optionen und einen Zeitstempel der Erstellung haben.

Umfragen verwalten:

  • Benutzer sollten in der Lage sein, die Frage oder Optionen einer vorhandenen Umfrage zu aktualisieren.
  • Benutzer sollten in der Lage sein, eine Umfrage zu löschen.

In Umfragen abstimmen:

  • Benutzer sollten in einer Umfrage für eine der Optionen stimmen können.
  • Jeder Benutzer kann nur einmal pro Umfrage abstimmen.

Umfrageergebnisse anzeigen:

  • Benutzer sollten in der Lage sein, die aktuellen Ergebnisse einer Umfrage anzuzeigen, einschließlich der Anzahl der Stimmen für jede Option.

Umfragedaten:

  • Speichern Sie Umfragen, Optionen und Abstimmungen so, dass ein effizienter Abruf und Aktualisierungen möglich sind.
  • Stellen Sie die Datenintegrität und -konsistenz sicher, insbesondere wenn mehrere Benutzer gleichzeitig abstimmen.

Implementierungsdetails

Funktionen/Methoden:

Umfrage erstellen

Umfrage erstellen :

  • Eingabe: Frage (Zeichenfolge), Optionen (Array von Zeichenfolgen)
  • Ausgabe: pollId (string), message (string)
  • Beispiel: createPoll("Was ist deine Lieblingsfarbe?", ["Rot", "Blau", "Grün", "Gelb"]) gibt {"pollId": "123", "message" zurück : „Umfrage erfolgreich erstellt.“}

Umfrage aktualisieren

UpdateUmfrage :

  • Eingabe: pollId (Zeichenfolge), Frage (Zeichenfolge), Optionen (Array von Zeichenfolgen)
  • Ausgabe: Nachricht (Zeichenfolge)
  • Beispiel: updatePoll("123", "Frage aktualisiert?", ["Option1", "Option2"]) gibt {"message": "Umfrage erfolgreich aktualisiert."} zurück

Umfrage löschen

löschenPoll :

  • Eingabe: pollId (string)
  • Ausgabe: Nachricht (Zeichenfolge)
  • Beispiel: deletePoll("123") gibt {"message": "Umfrage erfolgreich gelöscht."} zurück

In der Umfrage abstimmen

voteInPoll :

  • Eingabe: pollId (string), userId (string), option (string)
  • Ausgabe: Nachricht (Zeichenfolge)
  • Beispiel: voteInPoll("123", "user1", "Option1") gibt {"message": "Abstimmung erfolgreich abgegeben."} zurück.

Umfrageergebnisse anzeigen

viewPollResults :

  • Eingabe: pollId (string)
  • Ausgabe: pollId (Zeichenfolge), Frage (Zeichenfolge), Ergebnisse (Objekt mit Optionsschlüsseln und Stimmenzahlwerten)
  • Beispiel: viewPollResults("123") gibt {"pollId": "123", "question": "Was ist Ihre Lieblingsfarbe?", "results": {"Red": 10, "Blue ": 5, "Grün": 3, "Gelb": 2}}

Datenmodelle

  • Umfrage:
{
  "pollId": "123",
  "question": "What is your favorite color?",
  "options": ["Red", "Blue", "Green", "Yellow"],
  "createdAt": "2024-07-11T00:00:00Z"
}
Nach dem Login kopieren
  • Abstimmung:
{
  "pollId": "123",
  "userId": "user1",
  "option": "Red",
  "timestamp": "2024-07-11T01:00:00Z"
}
Nach dem Login kopieren

Implementierungsdetails

Dieser Code definiert ein grundlegendes Abfragesystem mithilfe von JavaScript-Klassen. Es ermöglicht die Erstellung, Verwaltung und Abstimmung in Umfragen. Lassen Sie uns jeden Teil des Codes aufschlüsseln:

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.

Nach dem Login kopieren

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

Das obige ist der detaillierte Inhalt vonLow-Level-Design: Umfragesystem. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!