Last active
June 23, 2021 16:09
-
-
Save gomezcabo/c83e81628e60dc7e1ae8d0cecf3b186c to your computer and use it in GitHub Desktop.
Object Map excercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.typescriptlang.org/play?ssl=20&ssc=1&pln=1&pc=1#code/MYewdgzgLgBAZgJxAWwKJigglgUwjAXhgAosocEBDAIwBscAuGSsATwEpCA+GAbQDpBZCjXoBdfghwATAK7AcxYiGoArADR8A1jlaaAbpVpjOBHgG8AUDBswVq3jtZjCMQ7Wu2pUWQjB21TwBfTXMg9ktLOFkwYCgscADVHDiAWUoABwAeABUuYk8oAAscAHk1FKgmHPVPJ3SMjIomYi0mJxA4GBzTHmhsMABzWpt3WRwGpoQWtu7HXU7uk24YGK0wEAB3MFrOKxtvX39EFHRMXAgC2xhy5Lj+HAxsPGJisoq49n5kTKVHA2WZm0ukmFFazHwHS6PQMRnGoIQxH07BMIxg7AA3JYgljLKBILBkKxbpVXOZmEwAIyaahMABMmmATAAzDAcXjwNAYGAcJsSXFXPZKg1iET+VBNFoVgADJwAfQyUjgWAAHgwACTmLRBaUGFaUgAMRpgACo3JjIviICB6PxaCBBsRyWKPhLubzxWyLUA | |
const fromEntries = (iterable: any) => [...iterable].reduce((obj, [key, val]) => { | |
obj[key] = val | |
return obj | |
}, {}) | |
function objectMap<T>( | |
theObject: T, | |
keyMapper: (k: keyof T) => string, | |
valueMapper: (k: T[keyof T]) => unknown, | |
) { | |
return fromEntries( | |
Object.entries(theObject).map(([k, v]) => [keyMapper(k as keyof T), valueMapper(v)]), | |
); | |
}; | |
const myObject = { a: 1, b: 2, c: 3 }; | |
const newObject = objectMap(myObject, k => `key_prefix:${k}`, v => 1000 * v); | |
console.log({ myObject, newObject }); | |
// | |
// Add to Object prototype | |
// | |
// Object.defineProperty(Object.prototype, "map", { | |
// get: function () { | |
// return (keyMapper, valueMapper) => objectMap(this, keyMapper, valueMapper); | |
// }, | |
// configurable: true, | |
// }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment