JavaScript (TypeScript/Angular): Shortest/Fastest method to set object keys/values based on previous logic? -


i'm attempting fill array objects objects same, , keys determined predefined item. know can multiple if...else, seems long method use , hoping more condensed and/or efficient without using external libraries.

current method fill array hardcoded objects:

fillarray(arr,n) {   while(arr.length < n) {     arr.push({         'x': math.round(math.random(),         'name': 'item' + arr.length + 1     });   } } 

example of i'd achieve using if:

fillarray(arr, n, type) {   while(arr.length < n) {     if ( type === 'type1' ) {       arr.push({         'x': math.round(math.random(),         'name': 'item' + arr.length + 1       });     } else if ( type === 'type2') {       arr.push({         'x': math.round(math.random(),         'y': math.round(math.random(),         'name': 'item' + arr.length + 1       });     }   } } 

in application use type of method dozen if items, , there similar methods well. not wish apply static typing these items, since application may require object keys dynamically added.

an idea had can't seem complete idea in head somehow pre-defining array of objects, , using find somehow apply each item in array type.

psuedo-code (untested):

mytypes = [{   type: 'type1', keys: ['x', 'name']},   {type: 'type2', keys: ['x', 'y', 'name'] }]; fillarray(arr,n, type) {   let currenttype = this.mytypes.find( mytypes => mytypes.type === type).keys   while(arr.length < n) {     // add loop iterate on each key/value here separately   } } 

would type of method work, efficient, , reasonable practice approach? there other standard practices type of array population dynamic keys?

moving dynamic properties object keys harm type safety. since typescript primary language, important concern. also, keys doesn't allow control property values.

it can hierarchy of classes or factory functions:

class type1 {   x = ...;   name = ...; }  class type2 extends type1 {   y = ...; }  const typesmap = { type1: type1, type2: type2 };  fillarray(arr, n, type) {   while(arr.length < n) {     arr.push(new typesmap[type])   } } 

the difference original code won't work if type incorrect or missing, may or may not desirable.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -