Created
November 13, 2014 21:56
-
-
Save buzzdecafe/933ac4018ec1b9f31831 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
function cond2() { | |
var cs = [].slice.call(arguments, 0, arguments.length - 1); | |
var ow = arguments[arguments.length - 1]; | |
return function() { | |
var i = -1; | |
while(++i < cs.length) { | |
var value = cs[i].apply(this, arguments); | |
if (value) { | |
return value; | |
} | |
} | |
return ow.apply(this, arguments); | |
}; | |
} | |
function ifTrue(pred, onSat) { | |
return function() { | |
return pred.apply(this, arguments) ? onSat.apply(this, arguments) : void 0; | |
}; | |
} | |
// example: | |
grade = cond2( | |
ifTrue(R.gte(__, 90), R.always('A')), | |
ifTrue(R.gte(__, 80), R.always('B')), | |
ifTrue(R.gte(__, 70), R.always('C')), | |
ifTrue(R.gte(__, 60), R.always('D')), | |
R.always('F') | |
); | |
grade(55) // => 'F' | |
grade(66) // => 'D' | |
grade(75) // => 'C' | |
grade(80) // => 'B' | |
grade(99) // => 'A' |
Nice, its extensible with variations, may be useful sometimes for the looks
function ifFalse(pred, onSat) {
return function() {
return pred.apply(this, arguments) ? void 0 : onSat.apply(this, arguments);
};
}
// example:
grade = cond2(
ifFalse(R.lte(__, 100), R.always('Nice try')),
ifTrue(R.gte(__, 90), R.always('A')),
ifTrue(R.gte(__, 80), R.always('B')),
);
log (grade(80)); // => 'B'
log (grade(101)); // => 'Nice try'
function ifAny(arr, onSat) {
return function() {
var i = -1;
while (++i < arr.length) { // hah ++i not i++
var pred = arr[i];
if(pred.apply(this, arguments)) {
return onSat.apply(this, arguments);
}
}
return void 0;
};
}
// example:
grade = cond2(
ifAny([R.gt(__, 70), R.lt(__, 50), R.eq(60)], R.always('Your good or bad')),
R.always('well..')
);
log (grade(49)); // => 'Your good or bad'
log (grade(59)); // => 'well...'
log (grade(60)); // => 'Your good or bad'
log (grade(61)); // => 'well...'
log (grade(71)); // => 'Your good or bad'
Not sure those are really needed, but it may be more extensible in the future compared to array tuples.
Otherwise i don't see why tuples wouln't work as well
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For comparison, here's the example with the cond function proposed in ramda/ramda#518: