Skip to content

Instantly share code, notes, and snippets.

@buzzdecafe
Created November 13, 2014 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzzdecafe/933ac4018ec1b9f31831 to your computer and use it in GitHub Desktop.
Save buzzdecafe/933ac4018ec1b9f31831 to your computer and use it in GitHub Desktop.
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'
@davidchambers
Copy link

For comparison, here's the example with the cond function proposed in ramda/ramda#518:

var grade = R.cond(
  [R.gte(_, 90), R.always('A')],
  [R.gte(_, 80), R.always('B')],
  [R.gte(_, 70), R.always('C')],
  [R.gte(_, 60), R.always('D')],
  [R.gte(_, 50), R.always('E')],
  [R.alwaysTrue, R.always('F')]
);

@fyyyyy
Copy link

fyyyyy commented Nov 13, 2014

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'

@fyyyyy
Copy link

fyyyyy commented Nov 13, 2014

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'

@fyyyyy
Copy link

fyyyyy commented Nov 13, 2014

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