radash icon indicating copy to clipboard operation
radash copied to clipboard

Allow filtering in MapEntries

Open stefaanv opened this issue 2 years ago • 2 comments

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 avatar Nov 20 '23 15:11 stefaanv

Pull request 367 created to resolv this issue

stefaanv avatar Nov 30 '23 20:11 stefaanv

So this is kind of like combining select with Object.entries and Object.fromEntries (and yours is obviously more performant).

Object.fromEntries(
  select(
    Object.entries(object),
    ([key]) => key !== 'power',
    ([key, value]) => [key.toUpperCase(), `${value}`],
  ),
)

Should it be a new function called selectEntries?

~I'd be open to a PR in Radashi.~

edit: Over at Radashi, we came to the conclusion that this feature request doesn't meet the project standards. See here for more context.

aleclarson avatar Jun 28 '24 02:06 aleclarson