“Luhn” Algorithm using ECMAScript 6

Luhn Algorithm (https://en.wikipedia.org/wiki/Luhn_algorithm) is a very popular algorithm among developers. It is mostly used for Credit Card number validations.

The basic idea is you have a set of numbers with length 15 and using these 15 digits you are calculating a check digit for the 16th position.

The Simplified algorithm definition as follows

  • Lets take a sample 15 digit number (123456789123456) and you need to get the check digit and complete the sequence.
  • First you need to reverse the number sequence – 654321987654321
  • You have to take the odd position numbers and need to multiply them by 2 – 12, 8, 4,18,14,10,6,2
  • If the multiplied value is grater than 9, we need to subtract 9 from them. – 3,8,4,9,5,1,6,2
  • The Even number list is not subjected to change – 5,3,1,8,6,4,2
  • We need to add those numbers together and need to get a total

(3+8+4+9+5+1+6+2)+(5+3+1+8+6+4+2) = 67

  • To get the check digit we need to subtract the output value from next 10th multiplier. In our case it is 70

70 – 67 = 3

Lets do this in ECMA6Script way…

ES6 Babel(ing)

ECMA Script 6 is the latest JavaScript technology enhancement released in 2015. Lets look at the basic features of ECMA6 with compared to old JavaScript.

  • let the var begin – ‘let’ is new keyword
  • use arrows not guns – arrow(=>) functions


let myFunction = (input1, input2) => {return input1 + input2}

which is similar to this

var myFunction = function(input1, input2){
return input1 + input2


But how I compile new ECMA6

Solution is Babel (https://babeljs.io/)
First lets create a workspace for our ECMA6 work.

mkdir es6 && cd es6

Create a empty file .babelrc in the working directory.

vim .babelrc

and paste below content

"presets": ["es2015"]

Then we will install babel-cli in the working directoty and install es2015 presets as well

npm install --save-dev babel-cli
npm install babel-preset-es2015 --save-dev

We will create a symbolic for babel executables located in node_modules/babel-cli/bin directory to our working directory.

Ex :

ln -s ./node_modules/babel-cli/bin/babel-node.js babel-node

Coding with ES6

This is a simple es6 code sample, create file recursion_es6.js and put below content inside it.

let catagories = [
{ id: "animal", "parent": null },
{ id: "mammel", "parent": "animal" },
{ id: "dog", "parent": "mammel" },
{ id: "cat", "parent": "mammel" },
{ id: "pug", "parent": "dog" },
{ id: "german shepard", "parent": "dog" },
{ id: "persian", "parent": "cat" },
{ id: "russian", "parent": "cat" }];

let makeTree = (catagories, parent) => {

let node = {};

.filter(elem => elem.parent === parent)
.forEach(elem => node[elem.id] = makeTree(catagories, elem.id));

return node;

console.log(JSON.stringify(makeTree(catagories, null), null, 2));

Then use babel-node to output your program

./babel-node recursion_es6.js

Happy Babeling…