Last active
December 3, 2022 22:00
-
-
Save oliverbenns/a7df87e09d637ba2b055d990c31ac9e1 to your computer and use it in GitHub Desktop.
Generate ecommerce promo code with Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Don't use characters that look similar in certain fonts, I/L/1, 0/O, B/8 etc. | |
const charSet = "ACDEFGHJKMNPQRSTUVWXYZ2345679"; | |
const delimiter = '-' | |
interface GeneratePromoCodeParams { | |
len: number; | |
} | |
export const generatePromoCode = (params: GeneratePromoCodeParams) => { | |
let result = ""; | |
for (let i = 0; i < params.len; i++) { | |
result += charSet.charAt(Math.floor(Math.random() * charSet.length)); | |
} | |
return result; | |
}; | |
// For display purposes | |
interface ChunkPromoCodeParams { | |
size: number; | |
} | |
export const chunkPromoCode = (code: string, params: ChunkPromoCodeParams) => { | |
let result = ""; | |
for (let i = 0; i < code.length; i++) { | |
result += code[i]; | |
if ((i + 1) % params.size === 0 && i !== code.length - 1) { | |
result += delimiter; | |
} | |
} | |
return result; | |
}; | |
// If user inputs with dashes, we can unchunk to then test validity. | |
export const unchunkPromoCode = (code: string) => { | |
return code.replaceAll(delimiter, ""); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment