Skip to content

Instantly share code, notes, and snippets.

@ryanhamley
Last active August 29, 2015 14:18
Show Gist options
  • Save ryanhamley/73140d5e9710a9a71fa0 to your computer and use it in GitHub Desktop.
Save ryanhamley/73140d5e9710a9a71fa0 to your computer and use it in GitHub Desktop.
Number prototype method to return a digit at a specified position or a slice between two specified positions
/**
* [getDigitAt method for numbers that will return either the digit at a specified position or the section of the number between two positions]
* @param {[number]} position1 [either the position to search for or the starting position of the slice]
* @param {[number]} position2 [*optional*, if supplied, this creates a slice and acts as the end position]
* @return {[number]} [either the digit at the specified position or the slice between the specified positions]
*/
Number.prototype.getDigitAt = function (position1, position2) {
//convert the number to a string to allow array-like access
var num = this.valueOf().toString();
//check to see if one or two arguments were supplied
if (arguments.length > 1) {
//ensure that the second argument is a valid number. if the first argument is not a number, the function will just default it to 0, but if the second argument is not a number, it will return NaN. to fix this, we choose to return the entire number.
if (!isNaN(position2) && position2 !== '') {
//if two arguments were supplied and the second is valid, get the selected section of num
num = num.slice(position1, position2);
}
//parse num back into a number in base 10 and return it.
} else {
//handle a decimal value by truncating the decimal with the bitwise operator |. this is only an issue with one argument, because when two arguments are supplied, the function just rounds them off in slice();
var _position = position1 | 0;
//if only one argument is supplied, simply return the digit at that position
return parseInt(num[_position], 10);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment