K
K
kachurinets2018-10-25 15:13:49
JavaScript
kachurinets, 2018-10-25 15:13:49

How to refactor such code?

I use the following function on the project to remove filter fields:

clearAllControl() {
        if (this.tableParam.region_id) {
            delete this.tableParam.region_id;
            this.searchForm.get('regionName').patchValue(null);
        }
        if (this.tableParam.district_id) {
            delete this.tableParam.district_id;
            this.searchForm.get('districtName').patchValue(null);
        }
        if (this.tableParam.area_id) {
            delete this.tableParam.area_id;
            this.searchForm.get('areaName').patchValue(null);
        }
        if (this.tableParam.city_id) {
            delete this.tableParam.city_id;
            this.searchForm.get('cityName').patchValue(null);
        }
        if (this.tableParam.place_id) {
            delete this.tableParam.place_id;
            this.searchForm.get('cityName').patchValue(null);
        }
        if (this.tableParam.name) {
            delete this.tableParam.name;
            this.searchForm.get('streetName').patchValue(null);
        }
        this.generateAddressesTable(this.tableParam);
    }


I don’t really like the implementation of this function, tell me how can I refactor it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-10-25
@kachurinets

We turn the common part of similar pieces of code into a function, and what they differ in, we will pass to this function as parameters:

[
  { del: 'region_id', search: 'regionName' },
  { del: 'district_id', search: 'districtName' },
  { del: 'area_id', search: 'areaName' },
  { del: 'city_id', search: 'cityName' },
  { del: 'place_id', search: 'cityName' },
  { del: 'name', search: 'streetName' },
].forEach(n => {
  if (this.tableParam[n.del]) {
    delete this.tableParam[n.del];
    this.searchForm.get(n.search).patchValue(null);
  }
});

D
dollar, 2018-10-25
@dollar

+++

const config = [
  'region', 'district', 'area', 'city',
  {id:'place_id', name:'cityName'}, {id:'name', name:'streetName'},
];

clearAllControl() {
  config.forEach(x=>{
    let id = x.id || (x + '_id');
    let name = x.name || (x + 'Name');
    if (this.tableParam[id]) {
      delete this.tableParam[id];
      this.searchForm.get(name).patchValue(null);
    }
  });
  this.generateAddressesTable(this.tableParam);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question