-
-
Notifications
You must be signed in to change notification settings - Fork 919
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: Luhn generation algorithms and tests (#980)
Co-authored-by: ST-DDT <[email protected]>
- Loading branch information
1 parent
4e38a70
commit c95826f
Showing
6 changed files
with
55 additions
and
50 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
/** | ||
* Checks that the given string passes the luhn algorithm. | ||
* | ||
* @param str The string to validate. | ||
*/ | ||
export function luhnCheck(str: string): boolean { | ||
return luhnChecksum(str) === 0; | ||
} | ||
|
||
/** | ||
* Calculates the luhn check value for the given string. | ||
* | ||
* @param str The string to calculate the check value for. | ||
* May contain the `L` placeholder at the end. | ||
*/ | ||
export function luhnCheckValue(str: string): number { | ||
const checksum = luhnChecksum(str.replace(/L?$/, '0')); | ||
return checksum === 0 ? 0 : 10 - checksum; | ||
} | ||
|
||
/** | ||
* Calculates the luhn checksum value for the given value. | ||
* | ||
* @param str The string to generate the checksum for. | ||
*/ | ||
function luhnChecksum(str: string): number { | ||
str = str.replace(/[\s-]/g, ''); | ||
let sum = 0; | ||
let alternate = false; | ||
for (let i = str.length - 1; i >= 0; i--) { | ||
let n = parseInt(str.substring(i, i + 1)); | ||
if (alternate) { | ||
n *= 2; | ||
if (n > 9) { | ||
n = (n % 10) + 1; | ||
} | ||
} | ||
sum += n; | ||
alternate = !alternate; | ||
} | ||
return sum % 10; | ||
} |
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
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
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
This file was deleted.
Oops, something went wrong.