Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sample Code Inaccurate #18

Closed
kevinleung23 opened this issue Aug 16, 2018 · 3 comments
Closed

Sample Code Inaccurate #18

kevinleung23 opened this issue Aug 16, 2018 · 3 comments

Comments

@kevinleung23
Copy link

first() documentation

Code (in sample):

const fullName = first(
    (t: string) => t === "Bill" && "Bill Barnes", // line 2
    t => t === "Hao" && "Hao Luo",
    t => t === "Kevin" && "Kevin Leung",
);

fullName("Bill").subscribe(console.log);    // Match{ value: "Bill Barnes" }
fullName("Hao").subscribe(console.log);     // Match{ value: "Hao Luo" }
fullName("Yomi").subscribe(console.log);    // undefined

Actual:

Match { score: 1, value: 'Bill Barnes' } // correct
Match { score: 1, value: false } // unexpected
Match { score: 1, value: false } // unexpected

When "Bill" argument is commented out (line 2), results are:

Match { score: 1, value: false }
Match { score: 1, value: 'Hao Luo' }
Match { score: 1, value: false }

If a fall through behavior is correct, samples are wrong.

@howlowck
Copy link

In the sample code, any unmatched string will return false (not undefined).

The first function still deems it as a "match" since it's not undefined, and returns the value (which is false).

@billba
Copy link
Owner

billba commented Aug 16, 2018

It feels hopelessly naive of you two to expect the sample code to actually work. Wake up and smell the coffee.

@billba
Copy link
Owner

billba commented Aug 16, 2018

I'll update the README shortly, but here's the correct code:

const fullName = first(
    (t: string) => t === "Bill" ? "Bill Barnes" : undefined,
    t => t === "Hao" ? "Hao Luo" : undefined,
    t => t === "Kevin" ? "Kevin Leung" : undefined,
);

In the real world I'd probably introduce a helper, e.g.

const getFullName = (
    name: string,
    fullName: string
) => (t: string) => t === name ? fullName : undefined;

const fullName = first(
    getFullName("Bill", "Bill Barnes"),
    getFullName("Hao", "Hao Luo"),
    getFullName("Kevin", "Kevin Leung"),
);

... but that probably would make the samples less clear.

@billba billba closed this as completed in a683965 Aug 16, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants