-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvotingApplication.js
85 lines (69 loc) · 2.51 KB
/
votingApplication.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const readline = require('readline');
const MAX_CANDIDATES = 4;
// Structure to hold candidate information
class Candidate {
constructor(name) {
this.name = name;
this.votes = 0;
}
}
// Function to initialize candidates
function initializeCandidates() {
return [
new Candidate("Ajay"),
new Candidate("Rohit"),
new Candidate("Shivendra"),
new Candidate("Ravi")
];
}
// Function to display candidates
function displayCandidates(candidates) {
console.log("\nList of Candidates Vote (s)");
console.log("------------------------------------------------\n");
candidates.forEach((candidate, i) => {
console.log(`[${i}] > ${candidate.name.padEnd(20, ' ')} ${candidate.votes}`);
});
}
function main() {
// Initialize candidates
const candidates = initializeCandidates();
// Display the voting box
console.log("+----------------------------------------------+");
console.log("| >> Vote for your CR << |");
console.log("+----------------------------------------------+\n");
// Display the list of candidates
displayCandidates(candidates);
// Create an interface for reading input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Function to prompt user for vote
function promptVote() {
rl.question('\nPress respective key to vote ::\n', (choice) => {
// Convert character choice to integer index
const index = parseInt(choice, 10);
// Check if index is valid
if (index >= 0 && index < MAX_CANDIDATES) {
// Increase the vote count for the selected candidate
candidates[index].votes++;
// Clear the screen (emulate by adding many new lines)
console.clear();
// Display the voting box
console.log("+----------------------------------------------+");
console.log("| >> Vote for your CR << |");
console.log("+----------------------------------------------+\n");
// Display updated candidates
displayCandidates(candidates);
} else {
console.log("Invalid choice. Please try again.");
}
// Prompt user for vote again
promptVote();
});
}
// Start the voting prompt
promptVote();
}
// Run the main function
main();