Last active
June 16, 2025 20:08
-
-
Save colinlord/9551c1116b90085ce79dab83229c48c0 to your computer and use it in GitHub Desktop.
rendezvous with cassidoo 6/16
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
// Given an array of strings representing the names of monarchs | |
// and their ordinal numbers, write a function that returns the | |
// list of names sorted first by name and then by their ordinal | |
// value (in Roman numerals), in ascending order. | |
function sortMonarchs(names) { | |
const romanToInt = (roman) => { | |
const romanMap = { | |
I: 1, | |
V: 5, | |
X: 10, | |
L: 50, | |
C: 100, | |
D: 500, | |
M: 1000 | |
}; | |
let total = 0; | |
for (let i = 0; i < roman.length; i++) { | |
const currentVal = romanMap[roman[i]]; | |
const nextVal = romanMap[roman[i + 1]]; | |
if (nextVal && currentVal < nextVal) { | |
total -= currentVal; | |
} else { | |
total += currentVal; | |
} | |
} | |
return total; | |
}; | |
return names.sort((a, b) => { | |
const [aName, aOrdinal] = a.split(" "); | |
const [bName, bOrdinal] = b.split(" "); | |
const nameComparison = aName.localeCompare(bName); | |
if (nameComparison !== 0) { | |
return nameComparison; | |
} | |
const aValue = romanToInt(aOrdinal); | |
const bValue = romanToInt(bOrdinal); | |
return aValue - bValue; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment