Here is my JS implementation of the algorithm which can be found on wikipedia.
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 |
/* Use at your own risk! Double test before deploying to prod! */ const reduce = require('lodash/reduce'); const calcChecksum = cusip => { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; const result = reduce(cusip, (acc, cur, idx) => { let value = 0; if (cur === '*') { value = 36; } else if (cur === '@') { value = 37; } else if (cur === '#') { value = 38; } else if (chars.indexOf(cur) === -1) { value = Number.parseInt(cur); } else { value = chars.indexOf(cur) + 10; } if (idx % 2) { value *= 2; } acc += Number.parseInt(value / 10) + (value % 10); return acc; }, 0); const checksum = (10 - (result % 10)) % 10; return checksum; } // Apple Inc.: 037833100 let result = calcChecksum('03783310'); console.log('Checking: 037833100', result); // Cisco Systems: 17275R102 result = calcChecksum('17275R10'); console.log('Checking: 17275R102', result); // Google Inc.: 38259P508 result = calcChecksum('38259P50'); console.log('Checking: 38259P508', result); // Microsoft Corporation: 594918104 result = calcChecksum('59491810'); console.log('Checking: 594918104', result); // Oracle Corporation: 68389X105 result = calcChecksum('68389X10'); console.log('Checking: 68389X105', result); |