Skip to content

Instantly share code, notes, and snippets.

@dianjuar
Created December 3, 2020 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dianjuar/30e3dcf353d495cd9d86802576bb281b to your computer and use it in GitHub Desktop.
Save dianjuar/30e3dcf353d495cd9d86802576bb281b to your computer and use it in GitHub Desktop.
Transform Array to Dictionary given a property of the object that is being managed on the array. Useful do operations over the array on cost O(n)
describe('transformArrayToDictionary', () => {
type myType = { id: string; data1: boolean; data2: boolean };
let array: myType[];
let expectedDic: { [key: string]: myType };
beforeEach(() => {
array = [
{
id: '1',
data1: true,
data2: true,
},
{
id: '2',
data1: true,
data2: false,
},
{
id: '3',
data1: false,
data2: false,
},
];
expectedDic = {
'1': {
id: '1',
data1: true,
data2: true,
},
'2': {
id: '2',
data1: true,
data2: false,
},
'3': {
id: '3',
data1: false,
data2: false,
},
};
});
it('should transform the array to the dictionary with the right structure', () => {
const dictionary = transformArrayToDictionary(array, 'id');
expect(dictionary).toEqual(expectedDic);
});
it('should override a value when the key is repeated', () => {
expectedDic['3'] = {
id: '3',
data1: true,
data2: true,
};
array.push({
id: '3',
data1: true,
data2: true,
});
const dictionary = transformArrayToDictionary(array, 'id');
expect(dictionary).toEqual(expectedDic);
});
it('should transform the data when the map function is passed', () => {
const expectedDicWithMap = {
'1': expectedDic['1'].data1,
'2': expectedDic['2'].data1,
'3': expectedDic['3'].data1,
};
const dictionary = transformArrayToDictionary(array, 'id', (val) => val.data1);
expect(dictionary).toEqual(expectedDicWithMap);
});
});
export function transformArrayToDictionary<T>(array: T[], keyUsed: keyof T): { [key: string]: T };
export function transformArrayToDictionary<T, ValueTransformed>(
array: T[],
keyUsed: keyof T,
map: (arrayValue: T) => ValueTransformed
): { [key: string]: ValueTransformed };
export function transformArrayToDictionary<T, ValueTransformed>(
array: T[],
keyUsed: keyof T,
map?: (arrayValue: T) => ValueTransformed
): { [key: string]: T } {
return array.reduce((acc, current: T) => {
const key = current[keyUsed].toString();
acc[key] = map ? map(current) : current;
return acc;
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment