deno_std
deno_std copied to clipboard
[feature request(collections)] add `invert`
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)
Can you please provide some use cases?
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
Those are good reasons. +1 from me. A PR would be welcome.
Completed in #4710.