Skip to content

Instantly share code, notes, and snippets.

@dmail
Created November 14, 2016 08:57
Show Gist options
  • Select an option

  • Save dmail/ee08ee1a26816874a4e1feddf349e738 to your computer and use it in GitHub Desktop.

Select an option

Save dmail/ee08ee1a26816874a4e1feddf349e738 to your computer and use it in GitHub Desktop.
Function returning how a name match the naming requirements for an array index in JavaScript
const STRING = 0; // name is a string it cannot be an array index
const INFINITE = 1; // name is casted to Infinity, NaN or -Infinity, it cannot be an array index
const FLOATING = 2; // name is casted to a floating number, it cannot be an array index
const NEGATIVE = 3; // name is casted to a negative integer, it cannot be an array index
const TOO_BIG = 4; // name is casted to a integer above Math.pow(2, 32) - 1, it cannot be an array index
const VALID = 5; // name is a valid array index
const maxArrayIndexValue = Math.pow(2, 32) - 1;
function getArrayIndexStatusForString(name) {
if (isNaN(name)) {
return STRING;
}
const number = Number(name);
if (isFinite(number) === false) {
return INFINITE;
}
if (Math.floor(number) !== number) {
return FLOATING;
}
if (number < 0) {
return NEGATIVE;
}
if (number > maxArrayIndexValue) {
return TOO_BIG;
}
return VALID;
}
function isPropertyNameValidArrayIndex(propertyName) {
return getArrayIndexStatusForString(propertyName) === VALID;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment