-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (65 loc) · 1.52 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
'use strict';
(function() {
function _splitDigits(num) {
return Array.prototype.map.call((num + '').trim().split(''), function(v) {
return parseInt(v, 10);
});
}
function _sum(num) {
return _splitDigits(num).reduce(function(c, v) {
return c + v;
});
}
/**
* create check sum.
*
* @param {string|number} num
* @return {number} check sum value
*/
function checkSum(num) {
if (num == null) {
return 0;
}
var doubled = _splitDigits(num).reverse().map(function(v, idx) {
return idx % 2 === 0 ? v * 2 : v;
});
var sum = doubled.reduce(function(tmp, v) {
return tmp + _sum(v);
}, 0);
var check = 10 - (sum % 10);
return check === 10 ? 0 : check;
}
/**
* validate num.
*
* @param {string|number} checkNumber check number
* @return {boolean} true: checkNumber is valid
*/
function isValid(checkNumber) {
if (checkNumber == null) {
return false;
}
var numbers = _splitDigits(checkNumber);
return numbers.pop() === checkSum(numbers.join(''));
}
/**
* create generate code
*
* @param {number} length generage
* @return {string} generaged digits value
*/
function generate(length) {
var len = length - 1;
var ary = new Array(len);
for (var i = 0; i < len; i++) {
ary.push(Math.floor(Math.random() * 10));
}
var num = ary.join('');
return num + '' + checkSum(num);
}
module.exports = {
isValid: isValid,
checkSum: checkSum,
generate: generate
};
}());