From 0638b466fd862705f1be699e7aaadbc839b92e1b Mon Sep 17 00:00:00 2001 From: David Guijarro Date: Tue, 23 Jun 2020 09:59:21 +0200 Subject: [PATCH] feat: mapValues --- src/map-values.spec.ts | 27 +++++++++++++++++++++++++++ src/map-values.ts | 17 +++++++++++++++++ tsconfig.json | 1 - 3 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/map-values.spec.ts create mode 100644 src/map-values.ts diff --git a/src/map-values.spec.ts b/src/map-values.spec.ts new file mode 100644 index 0000000..f59bf49 --- /dev/null +++ b/src/map-values.spec.ts @@ -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); + }); +}); diff --git a/src/map-values.ts b/src/map-values.ts new file mode 100644 index 0000000..f143142 --- /dev/null +++ b/src/map-values.ts @@ -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( + 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); +} diff --git a/tsconfig.json b/tsconfig.json index 1e79b51..354fca2 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,7 +17,6 @@ "paths": { "*": ["src/*", "node_modules/*"] }, - "jsx": "react", "esModuleInterop": true } }