Last active
July 2, 2016 15:27
-
-
Save DevJMD/a8992f57af541721fcbb30aa48c5f7e4 to your computer and use it in GitHub Desktop.
Alphabetical Ordering
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
let ingredients = ['Pepper', 'Apples', 'Bananas']; | |
function sortAlphabetical(array, reverse) { | |
// Regex alphabetical characters only. | |
const AcceptableCharacters = /^[a-zA-Z ]*$/; | |
// Check to see if each item starts with an alphbetical | |
// character. If not, then the array isn't vaild. | |
array.map((item) => { | |
const regexStringIsAlphabetitcal = AcceptableCharacters.test(item.substring(0, 1)); | |
if (!regexStringIsAlphabetitcal) { | |
throw new Error(`sortAlphabetical: Cannot use ${item} to sort an array alphabetically.`); | |
} | |
}); | |
// Compare A to B, checking if the alphabetical ordering of | |
// each letter for each word is correct. | |
array.sort((a, b) => { | |
let itemA = a.toLowerCase(), | |
itemB = b.toLowerCase(); | |
if (itemA < itemB) return -1; | |
if (itemA > itemB) return 1; | |
}); | |
// Reverse the ordering of the list if true. | |
if (reverse) array.reverse(); | |
return array; | |
} | |
console.log(sortAlphabetical(ingredients, false)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment