froebel icon indicating copy to clipboard operation
froebel copied to clipboard

Port of `_.invert`?

Open devinrhode2 opened this issue 1 year ago • 1 comments

https://github.com/lodash/lodash/blob/master/invert.js

devinrhode2 avatar May 08 '23 00:05 devinrhode2

Code sample provided without warranty

import { objectEntries, objectFromEntries } from 'ts-extras';

/**
 * Creates an object composed of the inverted keys and values of `object`.
 *
 * Return type copied from https://stackoverflow.com/a/56416192
 */
export const invertObject = <
  TObject extends Record<string, string>,
>(
  object: TObject,
): {
  [P in keyof TObject as TObject[P]]: P;
} => {
  return objectFromEntries(
    objectEntries(object).map(([key, value]) => [value, key]),
  ) as unknown as {
    [P in keyof TObject as TObject[P]]: P;
  };
};

devinrhode2 avatar May 08 '23 04:05 devinrhode2