Thursday, November 14, 2019

It's possible in JavaScript to make .reduce return an array if you pass in an empty array as a second parameter to .reduce after your function for magic contortions.

The first actor in the a/b logic is something you may set outside of the first item in your collection it would seem. You do so with a second parameter at the .reduce. All of a sudden .reduce seems less esoteric and something I might actually use in my day to day. This...

cleanFilter(oldArray:Array<FilterConfigurationModel>):Array<FilterConfigurationModel> {
   let newArray:Array<FilterConfigurationModel> = [];
   let counter:number = -1;
   oldArray.forEach((item)=>{
      let divide:string = " |>| ";
      if (item.displayName.indexOf(divide) >= 0) {
         let nameParts:Array<string> = item.displayName.split(divide);
         let copy = <FilterConfigurationModel>{
            ...item,
            displayName: nameParts[1]
         };
         if (!newArray[counter].filters) {
            newArray[counter].filters = new Array<FilterConfigurationModel>();
         }
         newArray[counter].filters.push(copy);
      } else {
         let copy = <FilterConfigurationModel>{
            ...item
         };
         newArray.push(copy);
         counter++;
      }
   });
   return newArray;
}

 
 

...may become:

cleanFilter(oldArray:Array<FilterConfigurationModel>):Array<FilterConfigurationModel> {
   let counter:number = -1;
   return oldArray.reduce((newArray, item) => {
      let divide:string = " |>| ";
      if (item.displayName.indexOf(divide) >= 0) {
         let nameParts:Array<string> = item.displayName.split(divide);
         let copy = <FilterConfigurationModel>{
            ...item,
            displayName: nameParts[1]
         };
         if (!newArray[counter].filters) {
            newArray[counter].filters = new Array<FilterConfigurationModel>();
         }
         newArray[counter].filters.push(copy);
      } else {
         let copy = <FilterConfigurationModel>{
            ...item
         };
         newArray.push(copy);
         counter++;
      }
      return newArray;
   }, new Array<FilterConfigurationModel>());
}

 
 

I suppose the example here is a TypeScript example in lieu of JavaScript example.

No comments:

Post a Comment