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

Allow filtering in MapEntries #364

Open
stefaanv opened this issue Nov 20, 2023 · 1 comment
Open

Allow filtering in MapEntries #364

stefaanv opened this issue Nov 20, 2023 · 1 comment

Comments

@stefaanv
Copy link

If the mapEntries() code is updates as below, it's function would extend to filtering the properties of the object

const mapEntries = <
    TKey extends string | number | symbol,
    TValue,
    TNewKey extends string | number | symbol,
    TNewValue,
>(
    obj: Record<TKey, TValue>,
    toEntry: (key: TKey, value: TValue) => [TNewKey, TNewValue] | undefined
): Record<TNewKey, TNewValue> => {
    if (!obj) return {} as Record<TNewKey, TNewValue>
    return Object.entries(obj).reduce(
        (acc, [key, value]) => {
            const alteredEntry = toEntry(key as TKey, value as TValue)
            if (alteredEntry) acc[alteredEntry[0]] = alteredEntry[1]
            return acc
        },
        {} as Record<TNewKey, TNewValue>
    )
}

The example could become

const ra = {
    name: 'Ra',
    power: 'sun',
    rank: 100,
    culture: 'egypt'
}

mapEntries(ra, (key, value) =>  (key !== 'power') ? [key.toUpperCase(), `${value}`] : undefined)
// returns { "NAME": "Ra", "RANK": "100", "CULTURE": "egypt" }
@stefaanv
Copy link
Author

Pull request 367 created to resolv this issue

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

Successfully merging a pull request may close this issue.

1 participant