Skip to content

Commit

Permalink
feat: mapValues
Browse files Browse the repository at this point in the history
  • Loading branch information
davguij committed Jun 23, 2020
1 parent afd44f8 commit 0638b46
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 1 deletion.
27 changes: 27 additions & 0 deletions src/map-values.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { mapValues } from './map-values';

describe('mapValues', () => {
it('should apply the callback to every value of the source', () => {
const o = {
one: 1,
two: 2,
three: 3,
four: 4,
};
const e = {
one: 2,
two: 4,
three: 6,
four: 8,
};
const result = mapValues(o, item => item + item);
expect(result).toEqual(e);
});

it('should support strings', () => {
const o = { one: 'one' };
const e = { one: 'ONE' };
const result = mapValues(o, item => item.toUpperCase());
expect(result).toEqual(e);
});
});
17 changes: 17 additions & 0 deletions src/map-values.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Creates an object with the same keys as the `source` object and values generated by running each own enumerable property of `source` thru the `fn` function.
*
* @param source Object to map the values from.
* @param fn Function to apply to each value.
*/

export function mapValues<T, K extends keyof T>(
source: T,
fn: (value: T[K], key: K) => T[K]
) {
const entries = Object.entries(source).map<[K, T[K]]>(([key, value]) => [
key as K,
fn(value, key as K),
]);
return Object.fromEntries(entries);
}
1 change: 0 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
"paths": {
"*": ["src/*", "node_modules/*"]
},
"jsx": "react",
"esModuleInterop": true
}
}

0 comments on commit 0638b46

Please sign in to comment.