Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.