Skip to content

Commit e876e85

Browse files
author
Devendra Parmar
committed
Solved the two questions of the JavaScript
1. Key value object provided by the user to generate the another object from the given function 2. Map the value of an array create object
1 parent 7f139da commit e876e85

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Write a JavaScript program to create an object with keys generated by running the provided function for each key. The object will have the same values as the provided object.
2+
3+
const mapKeys = (obj, fn) =>
4+
Object.keys(obj).reduce((acc, k) => {
5+
acc[fn(obj[k], k, obj)] = obj[k];
6+
return acc;
7+
}, {});
8+
9+
console.log(mapKeys({ name: "devendra", age: 22 }, (val, key) => key + val));
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Write a JavaScript program to map array values to an object using a function. The key-value pairs consist of the original value as the key and the mapped value.
2+
3+
// Note: Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new Array to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
4+
5+
const mapObject = (arr, fn) =>
6+
((a) => (
7+
(a = [arr, arr.map(fn)]),
8+
a[0].reduce((acc, val, index) => ((acc[val] = a[1][index]), acc), {})
9+
))();
10+
11+
const squareIt = (arr) => mapObject(arr, (a) => a * a);
12+
13+
console.log(squareIt([1, 2, 3]));

0 commit comments

Comments
 (0)