2020-02-26 11:55:15 +01:00
/ * *
* @ author n1073645 [ n1073645 @ gmail . com ]
* @ copyright Crown Copyright 2020
* @ license Apache - 2.0
* /
import Operation from "../Operation.mjs" ;
import OperationError from "../errors/OperationError.mjs" ;
/ * *
* Luhn Checksum operation
* /
class LuhnChecksum extends Operation {
/ * *
* LuhnChecksum constructor
* /
constructor ( ) {
super ( ) ;
this . name = "Luhn Checksum" ;
2020-03-05 16:19:23 +01:00
this . module = "Default" ;
this . description = "The Luhn algorithm, also known as the modulus 10 or mod 10 algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers and Canadian Social Insurance Numbers." ;
2020-02-26 11:55:15 +01:00
this . infoURL = "https://wikipedia.org/wiki/Luhn_algorithm" ;
this . inputType = "string" ;
2020-03-09 10:13:02 +01:00
this . outputType = "string" ;
2020-02-26 11:55:15 +01:00
this . args = [ ] ;
}
/ * *
2020-03-09 10:13:02 +01:00
* Generates the Luhn Checksum from the input .
*
* @ param { string } inputStr
2020-02-26 11:55:15 +01:00
* @ returns { number }
* /
2020-03-09 10:13:02 +01:00
checksum ( inputStr ) {
2020-02-26 11:55:15 +01:00
let even = false ;
2020-03-09 10:13:02 +01:00
return inputStr . split ( "" ) . reverse ( ) . reduce ( ( acc , elem ) => {
2020-02-26 11:55:15 +01:00
// Convert element to integer.
let temp = parseInt ( elem , 10 ) ;
// If element is not an integer.
if ( isNaN ( temp ) )
throw new OperationError ( "Character: " + elem + " is not a digit." ) ;
// If element is in an even position
if ( even ) {
// Double the element and add the quotient and remainder together.
temp = 2 * elem ;
temp = Math . floor ( temp / 10 ) + ( temp % 10 ) ;
}
even = ! even ;
return acc + temp ;
} , 0 ) % 10 ;
}
2020-03-09 10:13:02 +01:00
/ * *
* @ param { string } input
* @ param { Object [ ] } args
* @ returns { string }
* /
run ( input , args ) {
2020-03-12 15:41:46 +01:00
if ( ! input ) return "" ;
2020-03-09 10:37:34 +01:00
2020-03-12 15:41:46 +01:00
const checkSum = this . checksum ( input ) ;
let checkDigit = this . checksum ( input + "0" ) ;
checkDigit = checkDigit === 0 ? 0 : ( 10 - checkDigit ) ;
2020-03-09 10:37:34 +01:00
2020-03-12 15:41:46 +01:00
return ` Checksum: ${ checkSum }
Checkdigit : $ { checkDigit }
Luhn Validated String : $ { input + "" + checkDigit } ` ;
2020-03-09 10:13:02 +01:00
}
2020-02-26 11:55:15 +01:00
}
export default LuhnChecksum ;