Created
May 15, 2013 16:27
-
-
Save dtinth/5585272 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
// returns itself | |
var self = function(object) { | |
return object | |
} | |
var get = function(name) { | |
// returns a property of an object | |
return function(object) { | |
return object[name] | |
} | |
} | |
var call = function(fn) { | |
// apply a function on the object | |
var rest = Array.prototype.slice.call(arguments, 1) | |
return function(object) { | |
return fn(object).apply(object, rest) | |
} | |
} | |
var send = function(name) { | |
var rest = Array.prototype.slice.call(arguments, 1) | |
return call.apply(this, [get(name)].concat(rest)) | |
} | |
// ==== selector functions ==== | |
var max = function(criteria) { | |
return function(current, best) { | |
return criteria(current) > criteria(best) | |
} | |
} | |
var min = function(criteria) { | |
return function(current, best) { | |
return criteria(current) < criteria(best) | |
} | |
} | |
// ==== high level function ==== | |
var pick = function(better, array) { | |
var none = {}, best = none | |
array.forEach(function(item) { | |
if (best === none || better(item, best)) { | |
best = item | |
} | |
}) | |
return best | |
} | |
var sort = function(right, array) { | |
var out = array.slice() | |
out.sort(function(a, b) { | |
return right(a, b) ? 1 : -1 | |
}) | |
return out | |
} | |
// ==== utility ==== | |
var section = function(name) { | |
show('=== ' + name + ' ===') | |
} | |
// ==== test code ==== | |
var a = [ 2, 5, 1, 2, 30, 24 ] | |
section('Simple max & min') | |
show(pick(max(self), a)) | |
show(pick(min(self), a)) | |
var c = [ "apple", "Banana", "pumpkin", "elephant", "zebra", "bee" ]; | |
section('Simple max & min with string') | |
show(pick(max(self), c)) | |
show(pick(min(self), c)) | |
section('Simple max & min by length') | |
var length = get('length') | |
show(pick(max(length), c)) | |
show(pick(min(length), c)) | |
section('Simple string sort') | |
show(sort(max(self), c)) | |
show(sort(min(self), c)) | |
section('Sort string by length') | |
show(sort(max(length), c)) | |
show(sort(min(length), c)) | |
section('Case insensitive sorting') | |
var caseInsensitive = send('toLowerCase') | |
show(sort(max(caseInsensitive), c)) | |
show(sort(min(caseInsensitive), c)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment