0

In the skeleton of the following class

class Iterable<A> {

    filter( filter: ( value: A ) => boolean ): Iterable<A> { ... }

    map<B>( f: ( value: A, index?: number ) => B ): Iterable<B> { ...}

    collect = <B>( filter: ( value: A ) => boolean ) => ( mapper: ( value: A ) => B ): Iterable<B> => { ... }

}

there is a curried property collect which is implemented this way

collect = <B>( filter: ( value: A ) => boolean ) => ( mapper: ( value: A ) => B ): Iterable<B> => {
    return this.filter( filter ).map( mapper )
}

This property is basically a curried function that takes two functions as argument and returns an Iterable<B>. With this, being an Iterable<A>, it can be used in the following manner:

const it: Iterable<string> = this.collect<string>( f => true )( ( v: A ) => v.toString() )

Now, I would like to transform this property into a class method but I am failing to find the right syntax

  • declaring

    collect<B>( filter: ( value: A ) => boolean ): ( mapper: ( value: A ) => B ) => Iterable<B>
    

    will preserve its usage (see itabove), however I do not know how to implement it as the method expects to return a Function, not an Iterable

  • declaring

    collect<B>( filter: ( value: A ) => boolean ) => ( mapper: ( value: A ) => B ) : Iterable<B>
    

    is invalid...


Solution: (see @JLRishe and @NitzanTomer answers) I went for an explicit type declaration:

collect<B>(filter: (value: A) => boolean): (mapper: (value: A) => B) => Iterable<B> {
    return (mapper: (value: A) => B) => this.filter(filter).map(mapper);
}
2
  • Can you put the code for your class as well? For example what's this A, what does this.filter returns? etc.. Commented Mar 21, 2017 at 9:08
  • @NitzanTomer A is a generic, see my edits above with the skeleton of the class Commented Mar 21, 2017 at 9:20

2 Answers 2

1

You can implement it like this:

collect<B>(filter: (value: A) => boolean) {
    return (mapper: (value: A) => B) => this.filter(filter).map(mapper);
}
Sign up to request clarification or add additional context in comments.

Comments

1

How about

collect<B>(filter: (value: A) => boolean) {
    return (mapper: (value: A) => B): Iterable<B> => {
        return this.filter(filter).map(mapper);
    };
}

1 Comment

Thanks. Same solution as JLRishe... who has beaten you on the clock (according to SO)

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.