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

Missing solution for dictionary challenge #1038

Open
hatched-cristina opened this issue Jul 21, 2020 · 2 comments
Open

Missing solution for dictionary challenge #1038

hatched-cristina opened this issue Jul 21, 2020 · 2 comments

Comments

@hatched-cristina
Copy link

hatched-cristina commented Jul 21, 2020

The instructor mentions at the end of "Dictionary Solution" lesson that it will be available on the repo, but I don't see it there. After contacting support via Intercom, I was directed to leave an issue on the repo. Thanks!

I would imagine it would be this file, but filled in https://github.com/mike-works/typescript-fundamentals/blob/362113346f26fde233919a04a9e8a87f81c8e319/challenges/dict/src/index.ts

@jubeater
Copy link

jubeater commented Oct 19, 2020

here is the sol i have(map from video, reduce just mocked the map style)

export type Dict<T> = {
    [anyKeyWeWant: string]: T | undefined;
};

// Array.prototype.map, but for Dict
export function mapDict<T, S>(
    dict: Dict<T>,
    fn: (arg: T, idx: number) => S
): Dict<S> {
    const out: Dict<S> = {};
    Object.keys(dict).forEach((keyName, idx: number) => {
        const thisItem = dict[keyName];
        if (typeof thisItem !== 'undefined') {
            out[keyName] = fn(thisItem, idx);
        };
    });
    return out;
}

// Array.prototype.reduce, but for Dict
export function reduceDict<T, S>(
    dict: Dict<T>,
    fn: (cur: T, sum: S) => S,
    initVal: S
): S {
    let out: S = initVal;
    Object.keys(dict).forEach((keyName) => {
        const thisItem = dict[keyName];
        if (typeof thisItem !== 'undefined') {
            out = fn(thisItem, out);
        };
    });
    return out;
}

@it3xl
Copy link

it3xl commented Oct 10, 2021

Oh, many thanks.

Couple of thoughts.

To make tests compilable after

it("(compile) should have a default typeParam", () => {
    ...
it("(compile) should have a default typeParam of `any`", () => {

we have to replace type Dict<T> with type Dict<T = any>

export type Dict<T = any> = {
    [k:string]: T | undefined;
};

Btw, we don't always use summation in reducers. A more general term is aggregation, IMHO.
I would use aggr in place of sum, i.e. fn: (cur: T, aggr: S) => S, in place of fn: (cur: T, sum: S) => S,.
But then fn would be more expressive the same as Array.prototype.reduce.

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