isISIN.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import assertString from './util/assertString';
  2. var isin = /^[A-Z]{2}[0-9A-Z]{9}[0-9]$/; // this link details how the check digit is calculated:
  3. // https://www.isin.org/isin-format/. it is a little bit
  4. // odd in that it works with digits, not numbers. in order
  5. // to make only one pass through the ISIN characters, the
  6. // each alpha character is handled as 2 characters within
  7. // the loop.
  8. export default function isISIN(str) {
  9. assertString(str);
  10. if (!isin.test(str)) {
  11. return false;
  12. }
  13. var _double = true;
  14. var sum = 0; // convert values
  15. for (var i = str.length - 2; i >= 0; i--) {
  16. if (str[i] >= 'A' && str[i] <= 'Z') {
  17. var value = str[i].charCodeAt(0) - 55;
  18. var lo = value % 10;
  19. var hi = Math.trunc(value / 10); // letters have two digits, so handle the low order
  20. // and high order digits separately.
  21. for (var _i = 0, _arr = [lo, hi]; _i < _arr.length; _i++) {
  22. var digit = _arr[_i];
  23. if (_double) {
  24. if (digit >= 5) {
  25. sum += 1 + (digit - 5) * 2;
  26. } else {
  27. sum += digit * 2;
  28. }
  29. } else {
  30. sum += digit;
  31. }
  32. _double = !_double;
  33. }
  34. } else {
  35. var _digit = str[i].charCodeAt(0) - '0'.charCodeAt(0);
  36. if (_double) {
  37. if (_digit >= 5) {
  38. sum += 1 + (_digit - 5) * 2;
  39. } else {
  40. sum += _digit * 2;
  41. }
  42. } else {
  43. sum += _digit;
  44. }
  45. _double = !_double;
  46. }
  47. }
  48. var check = Math.trunc((sum + 9) / 10) * 10 - sum;
  49. return +str[str.length - 1] === check;
  50. }