Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change a function's name

I have a function which acts as a sort of focal point before calling my api.

I want to reduce the bloat a little by simplifying my if statements.

Currently I have a list of statements. 2 of which are shown below

    if (this.props.source === 1) {
      api.updateData01(id, data).then(res => {
        this.hideModal()
        this.props.updateData01()
        console.log('DATA UPDATED')
      })
    }
    if (this.props.source === 2) {
      api.updateData02(id, data).then(res => {
        this.hideModal()
        this.props.updateData02()
        console.log('DATA UPDATED')
      })
    }

I'd like to simplify it by bringing my if statements up and instead dynamically rename the functions.

Something along the lines of

    if(this.props.source === 1){
      //rename updateData to updateData01
    }
    if(this.props.source === 2){
      //rename updateData to updateData02
    }

    api.updateData01(id, data).then(res => {
      this.hideModal()
      this.props.updateData01()
      console.log('DATA UPDATED')
    })

I've never had to rename a function before so am unsure how to begin.

I've attempted something like this but it obviously wasn't going to work.

   if(this.props.source === 1){
      const dataSource = 01
    }
   api.updateData + datasource + (.....
like image 845
Neil Morgan Avatar asked Dec 11 '22 01:12

Neil Morgan


2 Answers

Instead of renaming your functions you could use dynamic property names to access the correct function based on a hash (api)

const api = {
    updateData01 : () =>{},
    updateData02 : () =>{},
    /*...*/
    updateData0N : () =>{}
}

api[`updateData0${this.props.source}`]().then(/*...*/)
like image 118
Dupocas Avatar answered Dec 12 '22 15:12

Dupocas


@Dupocas approach is probably the one I'd go with. That said, it's also possible to accomplish this with an array:

// your updateData prop would look something like this:
// this.props.arrFn = [() => console.log('1'), () => console.log('2')]

const fireByDataSource = (source) => this.props.arrFn[source - 1](id, data)

componentDidMount() {
    if(this.props.source) return fireByDataSource(this.props.source)

    api.updateData01(id, data).then(res => {
      this.hideModal()
      fireByDataSource(1)
      console.log('DATA UPDATED')
    })
}
like image 43
Jay Kariesch Avatar answered Dec 12 '22 13:12

Jay Kariesch