Skip to content

Instantly share code, notes, and snippets.

@colinlord
Last active June 16, 2025 20:08
Show Gist options
  • Save colinlord/9551c1116b90085ce79dab83229c48c0 to your computer and use it in GitHub Desktop.
Save colinlord/9551c1116b90085ce79dab83229c48c0 to your computer and use it in GitHub Desktop.
rendezvous with cassidoo 6/16
// 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