Created
April 16, 2012 12:01
-
-
Save phiggins42/2398212 to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<script> | |
var list = [0, -1, 1, -1, 0, null, 1]; | |
var sorter = function(direction){ | |
// returns a sort function which treats `null` as a special case, either 'always higher' (1) | |
// or 'always lower' (-1) | |
direction = direction || 1; | |
var up = direction > 0; | |
return function(a, b){ | |
var aa = a == null ? undefined : a, | |
bb = b == null ? undefined : b, | |
careabout = up ? aa : bb | |
; | |
return aa == bb ? 0 : aa > bb || careabout == undefined ? 1 : -1; | |
} | |
} | |
var higher = [].concat(list.sort(sorter(1))); | |
var lower = [].concat(list.sort(sorter(-1))); | |
console.log(lower[0] === null, lower); | |
console.log(higher[higher.length - 1] === null, higher); | |
// then, something that sorts something in a direction can use that direction to | |
// determine where the nulls end up. `list` above ranged from negative-one to one, | |
// with mixed zero and null values in between. If we want to view that list | |
// from highest value to descending, we'd want the nulls to be treated as | |
// 'always lower' so they appear at the end of the list. | |
// If we wanted to view the list from lowest value to highest value we'd want the | |
// nulls to be treated as `higher-than-anything` so they would appear at the bottom | |
// list. | |
var sortThisArray = function(arr, direction){ | |
var s = sorter(direction); | |
return arr.sort(function(a,b){ | |
return direction * s(a,b) | |
}); | |
} | |
console.log(sortThisArray(list, 1)); | |
console.log(sortThisArray(list, -1)); | |
</script> | |
</head> | |
<body> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment