Last active
August 29, 2015 14:18
-
-
Save microbial/ccb747eedc696b252cfa to your computer and use it in GitHub Desktop.
Resort a word list by sum of letter value
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
// 'abc, ghi, def, abd1, g4hi' => 'abc, abd1, def, ghi, g4hi' | |
// Ignores non-letters in valuation but preserves them in return | |
function resortByValue(group) { | |
function __getWordVal(word) { | |
var alphaVals = { | |
a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10, k: 11, l: 12, m: 13, | |
n: 14, o: 15,p: 16, q: 17, r: 18, s: 19, t: 20, u: 21, v: 22, w: 23, x: 24, y: 25, z: 26 | |
}, | |
wordSum = 0; | |
word.split('').forEach(function (char) { | |
wordSum += alphaVals[char] || 0; | |
}); | |
return wordSum; | |
} | |
function __promote(startPos, endPos, list) { | |
var startVal = list[startPos], | |
endVal = list[endPos]; | |
list[startPos] = endVal; | |
list[endPos] = startVal; | |
return list; | |
} | |
function __orderWordValList(group) { | |
var groupParts = group.constructor === Array ? group : group.split(','), | |
prevItemOrder, prevItem, prevItemValue, itemValue; | |
groupParts.forEach(function (item, itemOrder) { | |
item = item.trimLeft().toLowerCase(); | |
prevItemOrder = itemOrder - 1 > 0 ? itemOrder - 1 : 0; | |
prevItem = groupParts[prevItemOrder]; | |
prevItemValue = __getWordVal(prevItem); | |
itemValue = __getWordVal(item); | |
if (itemValue < prevItemValue) { | |
groupParts = __promote(itemOrder, prevItemOrder, groupParts); | |
__orderWordValList(groupParts); | |
} | |
}); | |
return groupParts; | |
} | |
return __orderWordValList(group).join(','); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment