// Secret key for generating codes (you can make this any random string)
const secretKey = "benIsAwesome";
const codeLength = 4;
// Simple hash function to make the code more unique and deterministic
function hashString(input) {
input = btoa(input);
//return input;
let hash = 0;
let result = '';
for (let i = 0; i < input.length; i++) {
hash = (hash << 5) - hash + input.charCodeAt(i);
hash = hash & hash; // Convert to 32bit integer
}
// Loop to extend the length of the result by rehashing
for (let j = 0; j < 5; j++) { // Adjust to control string length
hash = (hash << 5) - hash + secretKey.charCodeAt(j % secretKey.length);
result += Math.abs(hash).toString(36); // Append base-36 to the result
}
console.log(result);
return result;
}
// Function to generate the code
function getCode(id) {
const combined = id + secretKey; // Combine the id and secret key for uniqueness
let hashedString = hashString(combined); // Generate hash of the combined string
hashedString = hashedString.replace(/[^a-zA-Z]/g, ''); // Remove any non-letter characters
hashedString = hashedString.toUpperCase(); // Convert to uppercase
//console.log('Hashed string:', hashedString); // Log for debugging
return hashedString.substring(0, codeLength); // Return the first 'codeLength' characters
}
// Function to check if the entered code is valid
function checkCode(id, code) {
const generatedCode = getCode(id); // Get the correct code for the given id
return generatedCode === code; // Compare the entered code with the correct one
}
// Example usage
for (let i = 0; i < 20; i++) {
// Log generated codes for levels 0 to 19
console.log(`Level ${i}: Code = ${getCode(i)}`);
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.