Created
October 14, 2015 04:35
-
-
Save chadfurman/d2f615882ed233b53f81 to your computer and use it in GitHub Desktop.
not quite
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
function sortByPath(arr, path) { | |
var index, values, returnArr; | |
console.log(arguments); | |
var argsList = Array.prototype.slice.call(arguments,2); | |
var possibleFunc = argsList.splice(-1,1)[0]; | |
console.log('possibleFunc', possibleFunc); | |
console.log('argsList', argsList); | |
var compare = function (a,b) { | |
if (a < b) { | |
return -1; | |
} else if (a > b) { | |
return 1; | |
} | |
return 0 | |
} | |
if (typeof possibleFunc === 'function') { | |
console.log('compare function!'); | |
compare = possibleFunc; | |
} else if ( possibleFunc === 'str' ) { | |
console.log('string sorting!'); | |
compare = function (a,b) { | |
return b.localeCompare(a); | |
} | |
return arr.sort(compare); | |
} else { | |
console.log('default compare!'); | |
argsList.push(possibleFunc); | |
} | |
values = []; | |
for (index in arr) { | |
values.push({value: getValue(arr[index], path, argsList), index: index}); | |
} | |
values.sort(function (a,b) { | |
return compare(a.value, b.value); | |
}); | |
console.log(values); | |
returnArr = []; | |
for (index in values) { | |
originalItem = arr[values[index].index]; | |
returnArr.push(originalItem); | |
} | |
return returnArr; | |
} | |
function getValue(object, path, argsList) { | |
var part, partIndex, pathParts, currentItem, match, numArgs; | |
var paramList = []; | |
pathParts = path.split('.'); | |
currentItem = object; | |
for (partIndex in pathParts) { | |
part = pathParts[partIndex]; | |
if (match = part.match(/([^[]*)\[([\d]*)]/)) { | |
console.log('match1!', match); | |
// access array element at current object | |
currentItem = currentItem[match[1]][match[2]]; | |
} else if (match = part.match(/([^(]*)\(([\d]*)\)/)) { | |
console.log('match2!', match); | |
numArgs = match[2]; | |
while (numArgs--) { | |
paramList.push(argsList.shift()); | |
} | |
currentItem = currentItem[match[1]].call(currentItem, paramList); | |
// get number of args from argsList using splice | |
} else { | |
console.log('nomatch!', part); | |
currentItem = currentItem[part]; | |
} | |
console.log('--->', currentItem); | |
} | |
return currentItem; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment