Search code examples
javascriptecmascript-6ecmascript-2016

What is the best way for reducing multiple if statement?


I have a helper function that builds object with appropriate query properties. I use this object as a body in my promise request. What is the most elegant way for refactoring multiple if statements? Here is a function:

 getQueryParams = (query, pagination, sorting) => {
        let queryParam = {}

        if (pagination && pagination.pageNumber) {
            queryParam.page = `${pagination.pageNumber}`
        }
        if (pagination && pagination.rowsOnPage) {
            queryParam.size = `${pagination.rowsOnPage}`
        }
        if (query) {
            const updatedQuery = encodeURIComponent(query)
            queryParam.q = `${updatedQuery}`
        }
        if (sorting) {
            queryParam.sort = `${sorting.isDescending ? '-' : ''}${sorting.name}`
        }
        return service.get(`/my-url/`, queryParam).then(result => {
            return result
        })
    }

Solution

  • If service checks its parameters (as it should), you could benefit from the default parameters. Something like this:

    const getQueryParams = (
      query = '',
      pagination = {pageNumber: 0, rowsOnPage: 0},
      sorting = {isDescending: '', name: ''}
    ) => {
      const queryParam = {
        page: pagination.pageNumber,
        size: pagination.rowsOnPage,
        q: encodeURIComponent(query),
        sort: `${sorting.isDescending}${sorting.name}`    
      }
      return ...;
    };
    

    A live example to play with at jsfiddle.