1

The following appears to be valid:

interface IPredicate {
    (s: Product): boolean
    and(IPredicate): IPredicate
    or(IPredicate): IPredicate
}

If it is valid how could I implement it so that roughly the following works:

let a: IPredicate = (s: Something) => true
let b: IPredicate = (s: Something) => false
let c: IPredicate = a.and(b)

1 Answer 1

2

A bit more verbose:

interface IPredicate<T> {
    (item: T): boolean
    and(p: IPredicate<T>): IPredicate<T>;
    or(p: IPredicate<T>): IPredicate<T>;
}

function createPredicate<T>(source: (item: T) => boolean) {
    let predicate = source as IPredicate<T>;
    predicate.and = (another:IPredicate<T>) => createPredicate((item: T) => source(item) && another(item));
    predicate.or = (another:IPredicate<T>) => createPredicate((item: T) => source(item) || another(item));

    return predicate;
}

type Something = {};

let a: IPredicate<Something> = createPredicate((s: Something) => true);
let b: IPredicate<Something> = createPredicate((s: Something) => false);
let c: IPredicate<Something> = a.or(b);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.