3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

マイナンバーのチェックデジットを JavaScript で計算する

Last updated at Posted at 2015-11-20

Ruby 版 の記事をもとに JavaScript でコードを書きました。並行して JavaScript ライブラリの練習にも取り組みました。

for ループ

function validateMyNumber(myNumber) {

  if (!(typeof myNumber === 'string' || myNumber instanceof String)) {
    return false;
  }

  if (myNumber.length !== 12) {
    return false;
  }

  var sum = 0;

  for (var n = 1; n <= 11; ++n) {
    var p = parseInt(myNumber[11 - n]);
    var q = n < 7 ? n + 1 : n - 5;
    sum += p * q;
  }

  ret = sum % 11;

  if (ret <= 1) {
    ret = 0;
  }

  return parseInt(myNumber[myNumber.length - 1]) === 11 - ret;
}

console.log(true === validateMyNumber('123456789018'));

Array.from

ES6 から配列オブジェクトの生成に Array.from が使えます。

var myNumber = '123456789018';

var sum = Array
  .from({length: 11}, function(v, k) {
    var n = k + 1;
    var p = parseInt(myNumber[11 - n]);
    var q = n < 7 ? n + 1 : n - 5;

    return p * q;
  })
  .reduce((previous, current) => previous + current);

console.log(206 === sum);

RxJS

準備中。

Ramda

var R = require('ramda');

var myNumber = '123456789018';

var ret = R.sum(R.range(1, 11).map(function(n, k) {
  var p = parseInt(myNumber[11 - n]);
  var q = n < 7 ? n + 1 : n - 5;

  return p * q;
}));

console.log(206 === ret);
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?