deno_std icon indicating copy to clipboard operation
deno_std copied to clipboard

[feature request(collections)] add `invert`

Open scarf005 opened this issue 1 year ago • 3 comments

Is your feature request related to a problem? Please describe.

introduce invert and invertBy function similar to lodash.

Describe the solution you'd like

/**
 * @example
 * ```ts
 * invert({ a: 1, b: 2 }) // { 1: 'a', 2: 'b' }
 * invert({ a: 1, b: 1, c: 1 }) // { 1: 'c' }
 * ```
 */
export function invert<K extends keyof never, V extends keyof never>(
  obj: Record<K, V>
): Record<V, K> {
  return Object.fromEntries(Object.entries(obj).map(([key, value]) => [value, key]))
}

Describe alternatives you've considered

keeping it as-is, but it's often useful to invert keys and values of object (similar to how mapKeys and mapValues are used a lot)

scarf005 avatar May 07 '24 07:05 scarf005

Can you please provide some use cases?

iuioiua avatar May 08 '24 01:05 iuioiua

Can you please provide some use cases?

they're used often when implementing bimap (data needs to be indexed from both sides)

also existing usages: https://github.com/search?q=_.invert+language%3ATypeScript+&type=code&p=1

scarf005 avatar May 08 '24 02:05 scarf005

Those are good reasons. +1 from me. A PR would be welcome.

iuioiua avatar May 08 '24 02:05 iuioiua

Completed in #4710.

iuioiua avatar May 12 '24 23:05 iuioiua