简体   繁体   中英

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

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? ie, 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,
}

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM