Last active
November 9, 2019 17:22
-
-
Save marcmartino/d0b24d6153dae4b101c1c2cc64ec2f4c to your computer and use it in GitHub Desktop.
This file contains 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
type Tuple<T, U> = [T, U]; | |
type Predicate<T> = (value: T) => boolean; | |
type Callback<T, U> = (value: T) => U; | |
type Route<T, U> = <V>( | |
predicate: Predicate<T>, | |
callback: Callback<T, V> | |
) => RouteResponse<T, U | V>; | |
interface RouteResponse<T, U> { | |
addCondition: Route<T, U>; | |
executeCondition: (val: T) => U | void; | |
} | |
const composeRouteCallbacks = <T, U, V>( | |
[prevPred, prevCallback]: Tuple<Predicate<T>, Callback<T, U>>, | |
callback: Callback<T, V> | |
) => (x: T) => (prevPred(x) && prevCallback ? prevCallback(x) : callback(x)); | |
const composePredicates = <T>(prevPred: Predicate<T>, pred: Predicate<T>) => ( | |
x: T | |
) => prevPred(x) || pred(x); | |
const recursiveRoute = <T, U>( | |
prevPred: Predicate<T>, | |
prevCall: Callback<T, U> | |
) => <V>( | |
pred: Predicate<T>, | |
cb: Callback<T, V> | |
): RouteResponse<T, U | V> => { | |
const newPred = composePredicates(prevPred, pred); | |
const newCallback = composeRouteCallbacks([prevPred, prevCall], cb); | |
return { | |
addCondition: recursiveRoute(newPred, newCallback), | |
executeCondition: (val: T): U | V | void => { | |
return newPred(val) | |
? newCallback(val) | |
: console.log("no match found " + val); | |
} | |
}; | |
}; | |
export const conditionRoute = <T, U>( | |
pred: Predicate<T>, | |
callback: Callback<T, U> | |
) => { | |
const noParentRoute: ( | |
pred: Predicate<T>, | |
cb: Callback<T, U> | |
) => RouteResponse<T, void> = recursiveRoute(() => false, _ => void 0); | |
return noParentRoute(pred, callback); | |
}; | |
const first = conditionRoute( | |
(x: number) => x > 500000, | |
x => console.log("gt half mill") | |
); | |
const second = first.addCondition( | |
x => x % 2 === 0, | |
(x: number) => (console.log(`num was even ${x}`), x) | |
); | |
second.executeCondition(500011); // gt half mill | |
second.executeCondition(300001); // num was even 300001 | |
second.executeCondition(10); // no match found 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment