-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
74 lines (63 loc) · 2.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"use strict";
// Only export where a Node/Browerserify-esque environment is present
if(typeof exports !== 'undefined'){
exports.validate = validate;
}
// Only attach to `window` if it's present
if(typeof window !== 'undefined'){
window.nhsNumberValidator = {validate: validate};
}
/**
* Validate an NHS number
* @param {Number, String} nhsNumber The NHS number to validate. This may be a String or a number.
* @returns {Boolean} `true` IFF the NHS number validates, else `false`
**/
function validate(nhsNumber){
// pre-flight checks
if(
nhsNumber === undefined ||
nhsNumber === null ||
isNaN(Number(nhsNumber)) ||
nhsNumber.toString().length !== 10
){
return false;
}
// convert numbers to strings, for internal consistency
if(Number.isInteger(nhsNumber)){
nhsNumber = nhsNumber.toString();
}
// Step 1: Multiply each of the first 9 numbers by (11 - position indexed from 1)
// Step 2: Add the results together
// Step 3: Divide the total by 11 to get the remainder
var nhsNumberAsArray = nhsNumber.split('');
var remainder = nhsNumberAsArray.slice(0,9)
.map(multiplyByPosition)
.reduce(addTogether, 0) % 11;
var checkDigit = 11 - remainder;
// replace 11 for 0
if(checkDigit === 11){
checkDigit = 0;
}
var providedCheckDigit = nhsNumberAsArray[9];
// Do the check digits match?
return checkDigit === Number(providedCheckDigit);
}
/**
* Multiply a value by its position, using the NHS number strategy
* @param {Number} digit the single-digit portion of the number
* @param {Number} index The 0-indexed position of `digit` within the NHS number
* @returns {Number} the result of the 'multiply by (11-position)' calculation
**/
function multiplyByPosition(digit, index) {
// multiple each digit by 11 minus its position (indexed from 1)
return digit * (11 - (index+1));
}
/**
* Add two values together. Useful for use in `reduce` calls
* @param {Number} previousValue the initial value
* @param {Number} currentValue the value to add to the initial value
* @returns {Number} the sum of the two parameters
**/
function addTogether(previousValue, currentValue){
return previousValue + currentValue;
}