Abdallah Ghrb Abdallah Ghrb - 4 months ago 17
Javascript Question

Apply operators (+, -, *, /) to Eastern Arabic numbers using Javascript

Many answers has been found how to convert Eastern Arabic number (

٠١٢٣٤٥٦٧٨
) to Western Arabic number (
01234567
) & vise versa.

However, is there a way to apply mathematical operators on Eastern Arabic numbers .
I am looking for something like following :

'١٢٣'+'١١٢'==235
'١٢٣'-'١١٢'==-11
'٢'*'٣'==6
'١'==='٢' //false

Answer

You could extends Number class & override valueOf method (Solution based on ES6)

class EANum extends Number{
     constructor(){
         super();
         this.value=arguments[0];
     }
    valueOf(){
       return  Number( this.value.replace(/[٠١٢٣٤٥٦٧٨٩]/g,(d)=> d.charCodeAt(0) - 1632).replace(/[۰۱۲۳۴۵۶۷۸۹]/g, (d)=> d.charCodeAt(0) - 1776));
    }
    toString(){
       return this.valueOf();
    }

}

var a=new EANum('٣٤'),b=new EANum('١١');
console.log(a); // 
console.log(a+b); //45
console.log(a-b); //23
console.log(a*b); //374