I have a basic function accepts Temperature data as an argument and then perform a simple temperature conversion operation on the data How can we perform the same functionality using without mutating the object? i.e, the function should not mutate the argument passed in, it should rather return a copy
JavaScript
x
9
1
function temperature(args) {
2
convertToF = convertToC = temperatureConverter
3
return Object.assign({
4
args,
5
convertToF,
6
convertToC
7
}, w.weatherData(args))
8
}
9
I have some helper functions to help with conversion
JavaScript
1
21
21
1
function temperatureConverter(args) {
2
const bool = args.unit === 'F'
3
return (bool) ? self.Celsiusconverter(args) : self.fahrenheitConverter(args)
4
}
5
6
function Celsiusconverter(args) {
7
args.value = (args.value - 32) * (5 / 9)
8
args.unit = 'C'
9
return {
10
args
11
}
12
}
13
14
function fahrenheitConverter(args) {
15
args.value = (args.value * 9 / 5 + 32)
16
args.unit = 'F'
17
return {
18
args
19
}
20
}
21
the args object looks like so :
JavaScript
1
8
1
const objTemp1 = {
2
unit: 'C',
3
type: 'Temp',
4
date: '2010-04-20T00:00:00.000Z',
5
place: 'someCity',
6
value: 10,
7
}
8
Advertisement
Answer
so the functions will look like this, and that solves the issue
JavaScript
1
21
21
1
function temperatureConverter(args) {
2
const bool = newArgs.unit === 'F'
3
return (bool) ? self.Celsiusconverter(args) : self.fahrenheitConverter(args)
4
}
5
6
function Celsiusconverter(args) {
7
newArgs = {args}
8
newArgs.value = (newArgs.value - 32) * (5 / 9)
9
newArgs.unit = 'C'
10
return newArgs
11
12
}
13
14
function fahrenheitConverter(args) {
15
newArgs = {args}
16
newArgs.value = (newArgs.value * 9 / 5 + 32)
17
newArgs.unit = 'F'
18
return newArgs
19
20
}
21