Skip to content

Instantly share code, notes, and snippets.

@desandro
Created May 19, 2016 18:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save desandro/534215e2ccc039649dee6e6a3157945b to your computer and use it in GitHub Desktop.
Save desandro/534215e2ccc039649dee6e6a3157945b to your computer and use it in GitHub Desktop.
hash table vs. conditionals
// Get 1st, 2nd, 3rd, 4th, from 1, 2, 3, 4
// ignoring 11, 12, 13 for demo
// using conditionals
function suffixDate( date ) {
var lastDigit = date % 10;
if ( lastDigit == 1 ) {
return date + 'st';
} else if ( lastDigit == 2 ) {
return date + 'nd';
} else if ( lastDigit == 3 ) {
return date + 'rd';
}
return date + 'th';
}
// using hash table
var dateSuffices = {
1: 'st',
2: 'nd',
3: 'rd'
};
function suffixDate( date ) {
var lastDigit = date % 10;
var suffix = dateSuffices[ lastDigit ] || 'th';
return date + suffix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment