How to return an Immutable object from a factory function in JavaScript

Tags: , ,



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

 function temperature(args) {
    convertToF = convertToC = temperatureConverter
    return Object.assign({
        args,
        convertToF,
        convertToC
    }, w.weatherData(args))
}

I have some helper functions to help with conversion

 function temperatureConverter(args) {
        const bool = args.unit === 'F'
        return (bool) ? self.Celsiusconverter(args) : self.fahrenheitConverter(args)
    }

    function Celsiusconverter(args) {
        args.value = (args.value - 32) * (5 / 9)
        args.unit = 'C'
        return {
            ...args
        }
    }

     function fahrenheitConverter(args) {
        args.value = (args.value * 9 / 5 + 32)
        args.unit = 'F'
        return {
            ...args
        }
    }

the args object looks like so :

const objTemp1 = {
    unit: 'C',
    type: 'Temp',
    date: '2010-04-20T00:00:00.000Z',
    place: 'someCity',
    value: 10,
}

Answer

so the functions will look like this, and that solves the issue

function temperatureConverter(args) {
        const bool = newArgs.unit === 'F'
        return (bool) ? self.Celsiusconverter(args) : self.fahrenheitConverter(args)
    }

    function Celsiusconverter(args) {
        newArgs = {...args}
        newArgs.value = (newArgs.value - 32) * (5 / 9)
        newArgs.unit = 'C'
                return newArgs

    }

     function fahrenheitConverter(args) {
        newArgs = {...args}
        newArgs.value = (newArgs.value * 9 / 5 + 32)
        newArgs.unit = 'F'
                return newArgs

    }


Source: stackoverflow