Skip to content

Instantly share code, notes, and snippets.

@DScheglov
Last active December 20, 2019 11:37
Show Gist options
  • Save DScheglov/d78abc77cba995bea77084e9fbe6ab31 to your computer and use it in GitHub Desktop.
Save DScheglov/d78abc77cba995bea77084e9fbe6ab31 to your computer and use it in GitHub Desktop.
function MapValues<K extends string, S, D>(
source: { [k in K]: S },
mapper: (value: S, key: K, src: { [k in K]: S }) => D
): { [k in K]: D } {
const dest = {} as { [k in K]: D };
for (let key of Object.keys(source) as K[]) {
dest[key] = mapper(source[key], key, source)
}
return dest;
}
export const mapValues = (source, mapper) => Object.keys(source).reduce(
(dest, key) => {
dest[key] = mapper(source[key], key, source);
return dest;
},
{}
);
const MapValues = <K extends string, S, D>(
source: { [k in K]: S },
mapper: (value: S, key: K, src: { [k in K]: S }) => D
): { [key in K]: D } => (Object.keys(source) as K[]).reduce(
(dest: { [k in K]: D }, key: K): { [k in K]: D } => {
dest[key] = mapper(source[key], key, source);
return dest;
},
{} as { [key in K]: D}
);
@alex-malyita
Copy link

alex-malyita commented Dec 20, 2019

interface ICar {
    price: number;
    name: string;
}

const carSource: Record<string, ICar> = {
    first: {
        name: "BMW",
        price: 100000,
    },
    second: {
        name: "Mersede",
        price: 200000,
    },
};

const MULTIPLIER = 2;

let multiplyCarPrice = (car: ICar): ICar => ({
    ...car,
    price: car.price * MULTIPLIER,
});

function mapValues<T>(source: Record<string, T>, mapper: (T) => T): Record<string, T> {
    return Object.keys(source).reduce((dest, key): Record<string, T> => {
        dest[key] = mapper(source[key]);
        return dest;
    }, {});
}

mapValues(carSource, multiplyCarPrice);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment