Sunday, 11 March 2018

One line NHS Number checker

I didn't know this until recently, but the UK's NHS number is a rather smart device, and I ended up spending a few minutes looking at this page and then generating this checker:

const chechNhsNum = num => {
  let multiplier = 10;
  return num.split("").reduce((a, c) => {
    if(multiplier > 1){
      const semiTotal = ~~c * multiplier;
      multiplier--;
      return a + semiTotal;
    }else{
      return 11 - a % 11 > 9 ? false : ~~c === 11 - a % 11
    }
  }, 0);
};

Then I got to thinking how small I could make the checker and worked this up:

const validNHSnum=num=>num.split("").reduce((a,c)=>a.m>1?{a:a.a+~~c*a.m,m:a.m-1}:11-a.a%11>9?false:~~c===11-a.a%11,{a:0,m:10});

Which is sort of like the puzzles Mr Monks and I used to beat ourselves up with when we played Empire of Code. Running it through Babel produces this, which I guess is more readable:

var validNHSnum = function validNHSnum(num) {
  return num.split("").reduce(function (a, c) {
    return a.m > 1 ? { a: a.a + ~~c * a.m, m: a.m - 1 } : 11 - a.a % 11 > 9 ? false : ~~c === 11 - a.a % 11;
  }, { a: 0, m: 10 });
};