Skip to content

Instantly share code, notes, and snippets.

@olsonpm
Created October 31, 2018 16:27
Show Gist options
  • Save olsonpm/3e2b8e4d0cddc3d85e4c6877197b15ff to your computer and use it in GitHub Desktop.
Save olsonpm/3e2b8e4d0cddc3d85e4c6877197b15ff to your computer and use it in GitHub Desktop.
invertValueArrays
import * as _ from 'lodash';
//
// I couldn't figure out a clean way to write nor name this function. It's
// similar to lodash's "invertBy" except the values are arrays of strings.
//
// It's easiest examplained by example
//
// input
// {
// key1: ['val1', 'val2'],
// key2: ['val3', 'val1'],
// }
//
// output
// {
// val1: ['key1', 'key2'],
// val2: ['key1'],
// val3: ['key2'],
// val4: ['key2'],
// }
//
// I use this below to create a map of supported file extensions to parser
// names, which creates a helpful error message to detect duplicate file
// extensions handlers.
//
export const invertValueArrays = (
result: { [propName: string]: string[] },
valueArray: string[],
key: string
): { [propName: string]: string[] } => {
return valueArray.reduce((innerResult, value) => {
if (innerResult[value]) {
innerResult[value].push(key);
} else {
_.set(innerResult, value, [key]);
}
return innerResult;
}, result);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment