The following is the code snippet that is for the function addCandidate, which enables us to check the party irrespective of the case. Check it out, and if it works proper, push it in the main code of Election.sol
function toLower(string memory str) internal pure returns (string memory) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint256 i = 0; i < bStr.length; i++) {
// Uppercase characters are in the range 65-90
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
// Convert to lowercase by adding 32
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
function addCandidate(string calldata candidateName, string calldata candidatePoliticalParty) external onlyOwner {
if (s_electionStatus == ElectionState.ENDED) {
revert ElectionNotOpen();
}
// Convert the party name to lowercase for case insensitivity
string memory candidatePartyHash = toLower(candidatePoliticalParty);
for (uint256 i = 0; i < s_candidates.length; i++) {
// Compare parties in lowercase to avoid case sensitivity issues
if (keccak256(bytes(toLower(s_candidates[i].politicalParty))) == keccak256(bytes(candidatePartyHash))) {
revert PartyAlreadyExists();
}
}
// Add the candidate with the party name in original case
s_candidates.push(Candidate({
name: candidateName,
politicalParty: candidatePoliticalParty
}));
s_votesPerCandidate[candidatePartyHash] = 0;
emit CandidateAdded(candidateName, candidatePoliticalParty);
THE CASE INSENSITIVE PARTY CHECK(RESOLVED)
The following is the code snippet that is for the function
addCandidate
, which enables us to check the party irrespective of the case. Check it out, and if it works proper, push it in the main code of Election.solfunction toLower(string memory str) internal pure returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint256 i = 0; i < bStr.length; i++) { // Uppercase characters are in the range 65-90 if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { // Convert to lowercase by adding 32 bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); }
function addCandidate(string calldata candidateName, string calldata candidatePoliticalParty) external onlyOwner { if (s_electionStatus == ElectionState.ENDED) { revert ElectionNotOpen(); }
}