Created
November 27, 2012 18:19
-
-
Save wezoalves/4156018 to your computer and use it in GitHub Desktop.
return digit mod 10 based on a number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Author: Weslley Alves <[email protected]> | |
* Author URI: http://wezo.com.br | |
* Version: 0.0.1 | |
* License: GNU General Public License | |
* License URI: http://www.wezo.com.br/blog/license/gnu-general-public-license/ | |
* | |
* Examples: | |
* <script type="text/javascript"> | |
* | |
* var number = "5432"; | |
* var digit = ""; | |
* | |
* digit = number.mod10(); | |
* // digit return "1" | |
* | |
* digit = number.mod10(true); | |
* // digit return "54321" | |
* | |
* digit = number.mod10(true , "-"); | |
* // digit return "5432-1" | |
* | |
* digit = number.mod10(false , "-"); | |
* // digit return "1" | |
* | |
*/ | |
String.prototype.mod10 = function(concatenate , separator){ | |
var sum = 0; | |
var totalDigits = this.length; | |
for ( var i = 0; i < totalDigits; i++) { | |
sum += this[i] * (totalDigits + 1 - [i]); | |
} | |
sum = sum % 11; | |
sum = 11 - parseInt(sum); | |
sum = sum >= 10 ? 0 : sum; | |
if(concatenate == false || concatenate == undefined){ | |
return sum; | |
}else{ | |
if(separator == undefined || separator == false){ | |
separator = ""; | |
} | |
return this + separator + sum; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment