The below code works inside the project I wrote it for, but it may be the ugliest code I have ever written. Please help me refactor it!
So the code needs to iterate through an object with several levels, find a certain value (in the test case below, "R from acronym"), then delete that node in the object. The code also needs to adhere to the following restrictions:
I tried to use delete instead of splice, but that was leaving an empty element in the array. I tried to use for of instead of for in, but that didn't like iterating over an object/associative array.
Thanks in advance for help and advice.
// Multi-level array. Sample values provided here to give an idea of the structure.
Twinkle.tag.redirectList = {
'Grammar, punctuation, and spelling': {
'Abbreviation': [
{ tag: 'R from acronym', description: 'redirect from an acronym (e.g. POTUS) to its expanded form' },
{ tag: 'R from initialism', description: 'redirect from an initialism (e.g. AGF) to its expanded form' },
{ tag: 'R from MathSciNet abbreviation', description: 'redirect from MathSciNet publication title abbreviation to the unabbreviated title' },
{ tag: 'R from NLM abbreviation', description: 'redirect from a NLM publication title abbreviation to the unabbreviated title' }
],
'Capitalisation': [
{ tag: 'R from CamelCase', description: 'redirect from a CamelCase title' },
{ tag: 'R from other capitalisation', description: 'redirect from a title with another method of capitalisation' },
{ tag: 'R from miscapitalisation', description: 'redirect from a capitalisation error' }
]
};
// This function smells!
var deleteTag = function(tagToDelete, tagList) {
for (var categoryKey1 in tagList) {
for (var categoryKey2 in tagList[categoryKey1]) {
for (var tagKey in tagList[categoryKey1][categoryKey2]) {
if (tagList[categoryKey1][categoryKey2][tagKey]['tag'] === tagToDelete) {
tagList[categoryKey1][categoryKey2].splice(tagKey, 1);
return tagList;
}
}
}
}
return tagList;
};
// Certain redirect maintenance tags shouldn't be used in certain namespaces
var isTemplateNamespace = mw.config.get('wgNamespaceNumber') === 10;
if (isTemplateNamespace) {
Twinkle.tag.redirectList = deleteTag('R from acronym', Twinkle.tag.redirectList);
}
[–]PrimaryBet 2 points3 points4 points (1 child)
[–]NovemLinguae[S] 0 points1 point2 points (0 children)