codv
v1.1.1
Published
Generate and validates random codes with check digits
Downloads
5
Readme
Codv
Codv is a tiny library for generating arbitrary-sized codes with check digits.
Installation
yarn add codv
Usage
generateCode
Generates a random code.
import { generateCode } from 'codv'
const [code, checkDigits] = generateCode() // [ '25931', '49' ]
Parameters
bodyLength
: the length of the code's body. Default is 5.checkLength
: the length of the code's check digits. Default is 2.
generateHexCode
Generates a random hexadecimal code.
The check digits of a hexadecimal code are still decimal values, as they are also generated with the same modulo 11 algorithm as the decimal codes.
import { generateHexCode } from 'codv'
const [code, checkDigits] = generateHexCode() // [ 'b5ac9', '26' ]
Parameters
bodyLength
: the length of the code's body. Default is 5.checkLength
: the length of the code's check digits. Default is 2.
verifyCode
Verifies if a given a random code (decimal or hexadecimal) is valid.
import { verifyCode } from 'codv'
const code = verifyCode('25931', '49') // true
Parameters
body
: The code's body.checkDigits
: The check digits to validate against the body.
Example
Codv utilizes the modulo 11 algorithm for calculating the check digits, this is the same algorithm used by the CPF and a lot of other identifications numbers worldwide.
Generating a valid random CPF
import { generateCode } from 'codv'
const cpf = generateCode(9, 2)
console.log(cpf) // [ '471896067', '34' ]
Verifying a CPF
import { verifyCode } from './verifyCode'
console.log(verifyCode('471896067', '34')) // true
console.log(verifyCode('471896067', '35')) // false
Browser usage
<script src="https://unpkg.com/[email protected]/dist/bundle.js"></script>
Then:
Codv.generateCode() // (2) [ "83087", "99" ]