Refactoring JavaScript/TypeScript: Eliminating repeated code blocksConvert JavaScript String to be all lower case?How can I convert a string to boolean in JavaScript?endsWith in JavaScriptHow to skip to next iteration in jQuery.each() util?Sort array of objects by string property valueHow to check if an object is an array?.prop() vs .attr()Check whether a string matches a regex in JSWhat is TypeScript and why would I use it in place of JavaScript?Switch statement multiple cases in JavaScript

Convert a string of digits from words to an integer

Why aren't faces sharp in my f/1.8 portraits even though I'm carefully using center-point autofocus?

How to export all graphics from a notebook?

Windows 10 deletes lots of tiny files super slowly. Anything that can be done to speed it up?

Beyond Futuristic Technology for an Alien Warship?

Can an energy drink or chocolate before an exam be useful ? What sort of other edible goods be helpful?

How to identify whether a publisher is genuine or not?

Can RPi4 run simultaneously on dual band (WiFi 2.4GHz / 5GHz)?

French license plates

Duck, duck, gone!

What should I consider when deciding whether to delay an exam?

What does it mean by "my days-of-the-week underwear only go to Thursday" in this context?

Is there an in-universe explanation of how Frodo's arrival in Valinor was recorded in the Red Book?

What are one's options when facing religious discrimination at the airport?

GPLv3 forces us to make code available, but to who?

Why, even after his imprisonment, do people keep calling Hannibal Lecter "Doctor"?

If someone asks a question using “quién”, how can one shortly respond?

What is the meaning of colored vials next to some passive skills

Why isn't there armor to protect from spells in the Potterverse?

Is there a faster way or keyboard shortcut to close files without saving in Preview?

Why most footers have a background color has a divider of section?

Impossible violin chord, how to fix this?

A famous scholar sent me an unpublished draft of hers. Then she died. I think her work should be published. What should I do?

My first Hangman game in Python



Refactoring JavaScript/TypeScript: Eliminating repeated code blocks


Convert JavaScript String to be all lower case?How can I convert a string to boolean in JavaScript?endsWith in JavaScriptHow to skip to next iteration in jQuery.each() util?Sort array of objects by string property valueHow to check if an object is an array?.prop() vs .attr()Check whether a string matches a regex in JSWhat is TypeScript and why would I use it in place of JavaScript?Switch statement multiple cases in JavaScript






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








-2















How can I shorten this monster block? (Non-Array solution)



setFooTypeFlag(flag: string) 
switch (flag)
case 'a':
this.fooType.a = true;
this.fooType.b = false;
this.fooType.c = false;
this.fooType.d = false;
break;
case 'b'
this.fooType.a = false;
this.fooType.b = true;
this.fooType.c = false;
this.fooType.d = false;
break;
case 'c':
this.fooType.a = false;
this.fooType.b = false;
this.fooType.c = true;
this.fooType.d = false;
break;
case 'd':
this.fooType.a = false;
this.fooType.b = false;
this.fooType.c = false;
this.fooType.d = true;
break;











share|improve this question
































    -2















    How can I shorten this monster block? (Non-Array solution)



    setFooTypeFlag(flag: string) 
    switch (flag)
    case 'a':
    this.fooType.a = true;
    this.fooType.b = false;
    this.fooType.c = false;
    this.fooType.d = false;
    break;
    case 'b'
    this.fooType.a = false;
    this.fooType.b = true;
    this.fooType.c = false;
    this.fooType.d = false;
    break;
    case 'c':
    this.fooType.a = false;
    this.fooType.b = false;
    this.fooType.c = true;
    this.fooType.d = false;
    break;
    case 'd':
    this.fooType.a = false;
    this.fooType.b = false;
    this.fooType.c = false;
    this.fooType.d = true;
    break;











    share|improve this question




























      -2












      -2








      -2








      How can I shorten this monster block? (Non-Array solution)



      setFooTypeFlag(flag: string) 
      switch (flag)
      case 'a':
      this.fooType.a = true;
      this.fooType.b = false;
      this.fooType.c = false;
      this.fooType.d = false;
      break;
      case 'b'
      this.fooType.a = false;
      this.fooType.b = true;
      this.fooType.c = false;
      this.fooType.d = false;
      break;
      case 'c':
      this.fooType.a = false;
      this.fooType.b = false;
      this.fooType.c = true;
      this.fooType.d = false;
      break;
      case 'd':
      this.fooType.a = false;
      this.fooType.b = false;
      this.fooType.c = false;
      this.fooType.d = true;
      break;











      share|improve this question
















      How can I shorten this monster block? (Non-Array solution)



      setFooTypeFlag(flag: string) 
      switch (flag)
      case 'a':
      this.fooType.a = true;
      this.fooType.b = false;
      this.fooType.c = false;
      this.fooType.d = false;
      break;
      case 'b'
      this.fooType.a = false;
      this.fooType.b = true;
      this.fooType.c = false;
      this.fooType.d = false;
      break;
      case 'c':
      this.fooType.a = false;
      this.fooType.b = false;
      this.fooType.c = true;
      this.fooType.d = false;
      break;
      case 'd':
      this.fooType.a = false;
      this.fooType.b = false;
      this.fooType.c = false;
      this.fooType.d = true;
      break;








      javascript typescript switch-statement refactoring






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 28 at 11:06







      Lonely

















      asked Mar 28 at 10:53









      LonelyLonely

      1,5353 gold badges21 silver badges45 bronze badges




      1,5353 gold badges21 silver badges45 bronze badges

























          4 Answers
          4






          active

          oldest

          votes


















          3
















          Is it short enough for you? :)



          Basically, iterate on each key and just set everything to flag === key :)



          setFooTypeFlag(flag: string) 
          Object.keys(this.fooType).forEach(key =>
          this.fooType[key] = flag === key;
          );



          If at the beginning, this has no keys yet, please refer to the answer of Jack.






          share|improve this answer



























          • @jack ... which will work correctly ?

            – Jonas Wilms
            Mar 28 at 11:10











          • Sorry @JonasWilms - what would this refer to above? (I'm still not entirely clear about lexical this).

            – Jack Bashford
            Mar 28 at 11:11











          • @jack the same this as in setFooTypeFlag

            – Jonas Wilms
            Mar 28 at 11:12


















          1
















          Use a dynamic property name. This will work for any amount of possibilities, and it doesn't require you to initialise them all beforehand:



          setFooTypeFlag(flag: string) 
          var chars = ["a", "b", "c", "d"];
          for (var i = 0; i < chars.length; i++)
          this.fooType[chars[i]] = chars[i] == flag;







          share|improve this answer



























          • thank you Jack, the real implementation is not so easy in the code above, there are some function calls and assignments. Therefore I've thought, there is maybe a known pattern as grouped radio buttons work. I need an array-free solution, like to try lodash etc.

            – Lonely
            Mar 28 at 11:03











          • You can replace the if-else with this.fooType[chars[i]] = chars[i] == flag

            – adiga
            Mar 28 at 11:03












          • @Lonely for the code shared in the question, this is the correct solution.

            – adiga
            Mar 28 at 11:06






          • 1





            I'd use for(const flag of flags) but that is personal preference ...

            – Jonas Wilms
            Mar 28 at 11:08






          • 1





            @Lonely if there are properties other than a, b, c, d, they will also be set to boolean

            – adiga
            Mar 28 at 11:09



















          1
















          enum fooTypes 
          "a" = "a",
          "b" = "b",
          "c" = "c",
          "d" = "d"


          interface IFooFlags
          [key: string]: boolean;


          const defaultFooTypes = new Map<fooTypes, boolean>([
          [fooTypes.a, true],
          [fooTypes.b, true],
          [fooTypes.c, true],
          [fooTypes.d, true]
          ]);

          const fooTypesMappings = new Map<fooTypes, boolean[]>([
          [fooTypes.a, [true, false, false, false]],
          [fooTypes.b, [false, true, false, false]],
          [fooTypes.c, [false, false, true, false]],
          [fooTypes.d, [false, false, false, true]]
          ]);

          class MyClass
          private mappings = fooTypesMappings;
          private fooTypes = defaultFooTypes;

          private setFooTypes(values: boolean[]): void
          [...this.fooTypes.keys()].forEach((key, index) =>
          this.fooTypes.set(key, values[index])
          );


          // In modern engines you can return:
          // Object.fromEntries(this.fooTypes)
          public getFooTypes(): IFooFlags
          return [...this.fooTypes].reduce(
          (obj, 0: key, 1: val ) => ( ...obj, [key]: val ),

          );


          public setFooTypeFlag(flag: fooTypes): void
          const flagTypes = this.mappings.get(flag);
          if (!flagTypes)
          throw new Error("Invalid flag type");

          this.setFooTypes(flagTypes);



          const fooLover = new MyClass();
          fooLover.setFooTypeFlag(fooTypes.d);
          alert(JSON.stringify(fooLover.getFooTypes()));


          Here is a demo of it






          share|improve this answer


































            1
















            I also got inspired by the answer from @jack-bashford:



            class MyClass 
            private flags = [...Array(26)].map((_, i) => (i + 10).toString(36));
            private minObjectKeys = 4;

            public buildBaseObject(flag: string): any
            return this.getFlagPortion(flag).reduce(
            (obj, key) => ( ...obj, [key]: key === flag ),

            );


            private getFlagPortion(flag: string): string[]
            const sliceEndPositon = this.getSliceEndPosition(flag);
            return this.flags.slice(0, sliceEndPositon);


            private getSliceEndPosition(flag: string): number
            const flagPosition = this.flags.indexOf(flag) + 1;
            return flagPosition < this.minObjectKeys
            ? this.minObjectKeys
            : flagPosition;



            const fooLover = new MyClass();
            alert(JSON.stringify(fooLover.buildBaseObject("d")));


            Here is the demo






            share|improve this answer



























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );














              draft saved

              draft discarded
















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55395776%2frefactoring-javascript-typescript-eliminating-repeated-code-blocks%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3
















              Is it short enough for you? :)



              Basically, iterate on each key and just set everything to flag === key :)



              setFooTypeFlag(flag: string) 
              Object.keys(this.fooType).forEach(key =>
              this.fooType[key] = flag === key;
              );



              If at the beginning, this has no keys yet, please refer to the answer of Jack.






              share|improve this answer



























              • @jack ... which will work correctly ?

                – Jonas Wilms
                Mar 28 at 11:10











              • Sorry @JonasWilms - what would this refer to above? (I'm still not entirely clear about lexical this).

                – Jack Bashford
                Mar 28 at 11:11











              • @jack the same this as in setFooTypeFlag

                – Jonas Wilms
                Mar 28 at 11:12















              3
















              Is it short enough for you? :)



              Basically, iterate on each key and just set everything to flag === key :)



              setFooTypeFlag(flag: string) 
              Object.keys(this.fooType).forEach(key =>
              this.fooType[key] = flag === key;
              );



              If at the beginning, this has no keys yet, please refer to the answer of Jack.






              share|improve this answer



























              • @jack ... which will work correctly ?

                – Jonas Wilms
                Mar 28 at 11:10











              • Sorry @JonasWilms - what would this refer to above? (I'm still not entirely clear about lexical this).

                – Jack Bashford
                Mar 28 at 11:11











              • @jack the same this as in setFooTypeFlag

                – Jonas Wilms
                Mar 28 at 11:12













              3














              3










              3









              Is it short enough for you? :)



              Basically, iterate on each key and just set everything to flag === key :)



              setFooTypeFlag(flag: string) 
              Object.keys(this.fooType).forEach(key =>
              this.fooType[key] = flag === key;
              );



              If at the beginning, this has no keys yet, please refer to the answer of Jack.






              share|improve this answer















              Is it short enough for you? :)



              Basically, iterate on each key and just set everything to flag === key :)



              setFooTypeFlag(flag: string) 
              Object.keys(this.fooType).forEach(key =>
              this.fooType[key] = flag === key;
              );



              If at the beginning, this has no keys yet, please refer to the answer of Jack.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 28 at 11:03

























              answered Mar 28 at 10:56









              sjahansjahan

              4,0932 gold badges11 silver badges30 bronze badges




              4,0932 gold badges11 silver badges30 bronze badges















              • @jack ... which will work correctly ?

                – Jonas Wilms
                Mar 28 at 11:10











              • Sorry @JonasWilms - what would this refer to above? (I'm still not entirely clear about lexical this).

                – Jack Bashford
                Mar 28 at 11:11











              • @jack the same this as in setFooTypeFlag

                – Jonas Wilms
                Mar 28 at 11:12

















              • @jack ... which will work correctly ?

                – Jonas Wilms
                Mar 28 at 11:10











              • Sorry @JonasWilms - what would this refer to above? (I'm still not entirely clear about lexical this).

                – Jack Bashford
                Mar 28 at 11:11











              • @jack the same this as in setFooTypeFlag

                – Jonas Wilms
                Mar 28 at 11:12
















              @jack ... which will work correctly ?

              – Jonas Wilms
              Mar 28 at 11:10





              @jack ... which will work correctly ?

              – Jonas Wilms
              Mar 28 at 11:10













              Sorry @JonasWilms - what would this refer to above? (I'm still not entirely clear about lexical this).

              – Jack Bashford
              Mar 28 at 11:11





              Sorry @JonasWilms - what would this refer to above? (I'm still not entirely clear about lexical this).

              – Jack Bashford
              Mar 28 at 11:11













              @jack the same this as in setFooTypeFlag

              – Jonas Wilms
              Mar 28 at 11:12





              @jack the same this as in setFooTypeFlag

              – Jonas Wilms
              Mar 28 at 11:12













              1
















              Use a dynamic property name. This will work for any amount of possibilities, and it doesn't require you to initialise them all beforehand:



              setFooTypeFlag(flag: string) 
              var chars = ["a", "b", "c", "d"];
              for (var i = 0; i < chars.length; i++)
              this.fooType[chars[i]] = chars[i] == flag;







              share|improve this answer



























              • thank you Jack, the real implementation is not so easy in the code above, there are some function calls and assignments. Therefore I've thought, there is maybe a known pattern as grouped radio buttons work. I need an array-free solution, like to try lodash etc.

                – Lonely
                Mar 28 at 11:03











              • You can replace the if-else with this.fooType[chars[i]] = chars[i] == flag

                – adiga
                Mar 28 at 11:03












              • @Lonely for the code shared in the question, this is the correct solution.

                – adiga
                Mar 28 at 11:06






              • 1





                I'd use for(const flag of flags) but that is personal preference ...

                – Jonas Wilms
                Mar 28 at 11:08






              • 1





                @Lonely if there are properties other than a, b, c, d, they will also be set to boolean

                – adiga
                Mar 28 at 11:09
















              1
















              Use a dynamic property name. This will work for any amount of possibilities, and it doesn't require you to initialise them all beforehand:



              setFooTypeFlag(flag: string) 
              var chars = ["a", "b", "c", "d"];
              for (var i = 0; i < chars.length; i++)
              this.fooType[chars[i]] = chars[i] == flag;







              share|improve this answer



























              • thank you Jack, the real implementation is not so easy in the code above, there are some function calls and assignments. Therefore I've thought, there is maybe a known pattern as grouped radio buttons work. I need an array-free solution, like to try lodash etc.

                – Lonely
                Mar 28 at 11:03











              • You can replace the if-else with this.fooType[chars[i]] = chars[i] == flag

                – adiga
                Mar 28 at 11:03












              • @Lonely for the code shared in the question, this is the correct solution.

                – adiga
                Mar 28 at 11:06






              • 1





                I'd use for(const flag of flags) but that is personal preference ...

                – Jonas Wilms
                Mar 28 at 11:08






              • 1





                @Lonely if there are properties other than a, b, c, d, they will also be set to boolean

                – adiga
                Mar 28 at 11:09














              1














              1










              1









              Use a dynamic property name. This will work for any amount of possibilities, and it doesn't require you to initialise them all beforehand:



              setFooTypeFlag(flag: string) 
              var chars = ["a", "b", "c", "d"];
              for (var i = 0; i < chars.length; i++)
              this.fooType[chars[i]] = chars[i] == flag;







              share|improve this answer















              Use a dynamic property name. This will work for any amount of possibilities, and it doesn't require you to initialise them all beforehand:



              setFooTypeFlag(flag: string) 
              var chars = ["a", "b", "c", "d"];
              for (var i = 0; i < chars.length; i++)
              this.fooType[chars[i]] = chars[i] == flag;








              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 28 at 11:06

























              answered Mar 28 at 10:56









              Jack BashfordJack Bashford

              34.2k7 gold badges29 silver badges53 bronze badges




              34.2k7 gold badges29 silver badges53 bronze badges















              • thank you Jack, the real implementation is not so easy in the code above, there are some function calls and assignments. Therefore I've thought, there is maybe a known pattern as grouped radio buttons work. I need an array-free solution, like to try lodash etc.

                – Lonely
                Mar 28 at 11:03











              • You can replace the if-else with this.fooType[chars[i]] = chars[i] == flag

                – adiga
                Mar 28 at 11:03












              • @Lonely for the code shared in the question, this is the correct solution.

                – adiga
                Mar 28 at 11:06






              • 1





                I'd use for(const flag of flags) but that is personal preference ...

                – Jonas Wilms
                Mar 28 at 11:08






              • 1





                @Lonely if there are properties other than a, b, c, d, they will also be set to boolean

                – adiga
                Mar 28 at 11:09


















              • thank you Jack, the real implementation is not so easy in the code above, there are some function calls and assignments. Therefore I've thought, there is maybe a known pattern as grouped radio buttons work. I need an array-free solution, like to try lodash etc.

                – Lonely
                Mar 28 at 11:03











              • You can replace the if-else with this.fooType[chars[i]] = chars[i] == flag

                – adiga
                Mar 28 at 11:03












              • @Lonely for the code shared in the question, this is the correct solution.

                – adiga
                Mar 28 at 11:06






              • 1





                I'd use for(const flag of flags) but that is personal preference ...

                – Jonas Wilms
                Mar 28 at 11:08






              • 1





                @Lonely if there are properties other than a, b, c, d, they will also be set to boolean

                – adiga
                Mar 28 at 11:09

















              thank you Jack, the real implementation is not so easy in the code above, there are some function calls and assignments. Therefore I've thought, there is maybe a known pattern as grouped radio buttons work. I need an array-free solution, like to try lodash etc.

              – Lonely
              Mar 28 at 11:03





              thank you Jack, the real implementation is not so easy in the code above, there are some function calls and assignments. Therefore I've thought, there is maybe a known pattern as grouped radio buttons work. I need an array-free solution, like to try lodash etc.

              – Lonely
              Mar 28 at 11:03













              You can replace the if-else with this.fooType[chars[i]] = chars[i] == flag

              – adiga
              Mar 28 at 11:03






              You can replace the if-else with this.fooType[chars[i]] = chars[i] == flag

              – adiga
              Mar 28 at 11:03














              @Lonely for the code shared in the question, this is the correct solution.

              – adiga
              Mar 28 at 11:06





              @Lonely for the code shared in the question, this is the correct solution.

              – adiga
              Mar 28 at 11:06




              1




              1





              I'd use for(const flag of flags) but that is personal preference ...

              – Jonas Wilms
              Mar 28 at 11:08





              I'd use for(const flag of flags) but that is personal preference ...

              – Jonas Wilms
              Mar 28 at 11:08




              1




              1





              @Lonely if there are properties other than a, b, c, d, they will also be set to boolean

              – adiga
              Mar 28 at 11:09






              @Lonely if there are properties other than a, b, c, d, they will also be set to boolean

              – adiga
              Mar 28 at 11:09












              1
















              enum fooTypes 
              "a" = "a",
              "b" = "b",
              "c" = "c",
              "d" = "d"


              interface IFooFlags
              [key: string]: boolean;


              const defaultFooTypes = new Map<fooTypes, boolean>([
              [fooTypes.a, true],
              [fooTypes.b, true],
              [fooTypes.c, true],
              [fooTypes.d, true]
              ]);

              const fooTypesMappings = new Map<fooTypes, boolean[]>([
              [fooTypes.a, [true, false, false, false]],
              [fooTypes.b, [false, true, false, false]],
              [fooTypes.c, [false, false, true, false]],
              [fooTypes.d, [false, false, false, true]]
              ]);

              class MyClass
              private mappings = fooTypesMappings;
              private fooTypes = defaultFooTypes;

              private setFooTypes(values: boolean[]): void
              [...this.fooTypes.keys()].forEach((key, index) =>
              this.fooTypes.set(key, values[index])
              );


              // In modern engines you can return:
              // Object.fromEntries(this.fooTypes)
              public getFooTypes(): IFooFlags
              return [...this.fooTypes].reduce(
              (obj, 0: key, 1: val ) => ( ...obj, [key]: val ),

              );


              public setFooTypeFlag(flag: fooTypes): void
              const flagTypes = this.mappings.get(flag);
              if (!flagTypes)
              throw new Error("Invalid flag type");

              this.setFooTypes(flagTypes);



              const fooLover = new MyClass();
              fooLover.setFooTypeFlag(fooTypes.d);
              alert(JSON.stringify(fooLover.getFooTypes()));


              Here is a demo of it






              share|improve this answer































                1
















                enum fooTypes 
                "a" = "a",
                "b" = "b",
                "c" = "c",
                "d" = "d"


                interface IFooFlags
                [key: string]: boolean;


                const defaultFooTypes = new Map<fooTypes, boolean>([
                [fooTypes.a, true],
                [fooTypes.b, true],
                [fooTypes.c, true],
                [fooTypes.d, true]
                ]);

                const fooTypesMappings = new Map<fooTypes, boolean[]>([
                [fooTypes.a, [true, false, false, false]],
                [fooTypes.b, [false, true, false, false]],
                [fooTypes.c, [false, false, true, false]],
                [fooTypes.d, [false, false, false, true]]
                ]);

                class MyClass
                private mappings = fooTypesMappings;
                private fooTypes = defaultFooTypes;

                private setFooTypes(values: boolean[]): void
                [...this.fooTypes.keys()].forEach((key, index) =>
                this.fooTypes.set(key, values[index])
                );


                // In modern engines you can return:
                // Object.fromEntries(this.fooTypes)
                public getFooTypes(): IFooFlags
                return [...this.fooTypes].reduce(
                (obj, 0: key, 1: val ) => ( ...obj, [key]: val ),

                );


                public setFooTypeFlag(flag: fooTypes): void
                const flagTypes = this.mappings.get(flag);
                if (!flagTypes)
                throw new Error("Invalid flag type");

                this.setFooTypes(flagTypes);



                const fooLover = new MyClass();
                fooLover.setFooTypeFlag(fooTypes.d);
                alert(JSON.stringify(fooLover.getFooTypes()));


                Here is a demo of it






                share|improve this answer





























                  1














                  1










                  1









                  enum fooTypes 
                  "a" = "a",
                  "b" = "b",
                  "c" = "c",
                  "d" = "d"


                  interface IFooFlags
                  [key: string]: boolean;


                  const defaultFooTypes = new Map<fooTypes, boolean>([
                  [fooTypes.a, true],
                  [fooTypes.b, true],
                  [fooTypes.c, true],
                  [fooTypes.d, true]
                  ]);

                  const fooTypesMappings = new Map<fooTypes, boolean[]>([
                  [fooTypes.a, [true, false, false, false]],
                  [fooTypes.b, [false, true, false, false]],
                  [fooTypes.c, [false, false, true, false]],
                  [fooTypes.d, [false, false, false, true]]
                  ]);

                  class MyClass
                  private mappings = fooTypesMappings;
                  private fooTypes = defaultFooTypes;

                  private setFooTypes(values: boolean[]): void
                  [...this.fooTypes.keys()].forEach((key, index) =>
                  this.fooTypes.set(key, values[index])
                  );


                  // In modern engines you can return:
                  // Object.fromEntries(this.fooTypes)
                  public getFooTypes(): IFooFlags
                  return [...this.fooTypes].reduce(
                  (obj, 0: key, 1: val ) => ( ...obj, [key]: val ),

                  );


                  public setFooTypeFlag(flag: fooTypes): void
                  const flagTypes = this.mappings.get(flag);
                  if (!flagTypes)
                  throw new Error("Invalid flag type");

                  this.setFooTypes(flagTypes);



                  const fooLover = new MyClass();
                  fooLover.setFooTypeFlag(fooTypes.d);
                  alert(JSON.stringify(fooLover.getFooTypes()));


                  Here is a demo of it






                  share|improve this answer















                  enum fooTypes 
                  "a" = "a",
                  "b" = "b",
                  "c" = "c",
                  "d" = "d"


                  interface IFooFlags
                  [key: string]: boolean;


                  const defaultFooTypes = new Map<fooTypes, boolean>([
                  [fooTypes.a, true],
                  [fooTypes.b, true],
                  [fooTypes.c, true],
                  [fooTypes.d, true]
                  ]);

                  const fooTypesMappings = new Map<fooTypes, boolean[]>([
                  [fooTypes.a, [true, false, false, false]],
                  [fooTypes.b, [false, true, false, false]],
                  [fooTypes.c, [false, false, true, false]],
                  [fooTypes.d, [false, false, false, true]]
                  ]);

                  class MyClass
                  private mappings = fooTypesMappings;
                  private fooTypes = defaultFooTypes;

                  private setFooTypes(values: boolean[]): void
                  [...this.fooTypes.keys()].forEach((key, index) =>
                  this.fooTypes.set(key, values[index])
                  );


                  // In modern engines you can return:
                  // Object.fromEntries(this.fooTypes)
                  public getFooTypes(): IFooFlags
                  return [...this.fooTypes].reduce(
                  (obj, 0: key, 1: val ) => ( ...obj, [key]: val ),

                  );


                  public setFooTypeFlag(flag: fooTypes): void
                  const flagTypes = this.mappings.get(flag);
                  if (!flagTypes)
                  throw new Error("Invalid flag type");

                  this.setFooTypes(flagTypes);



                  const fooLover = new MyClass();
                  fooLover.setFooTypeFlag(fooTypes.d);
                  alert(JSON.stringify(fooLover.getFooTypes()));


                  Here is a demo of it







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 28 at 20:23

























                  answered Mar 28 at 19:20









                  Ali HabibzadehAli Habibzadeh

                  8,8612 gold badges43 silver badges66 bronze badges




                  8,8612 gold badges43 silver badges66 bronze badges
























                      1
















                      I also got inspired by the answer from @jack-bashford:



                      class MyClass 
                      private flags = [...Array(26)].map((_, i) => (i + 10).toString(36));
                      private minObjectKeys = 4;

                      public buildBaseObject(flag: string): any
                      return this.getFlagPortion(flag).reduce(
                      (obj, key) => ( ...obj, [key]: key === flag ),

                      );


                      private getFlagPortion(flag: string): string[]
                      const sliceEndPositon = this.getSliceEndPosition(flag);
                      return this.flags.slice(0, sliceEndPositon);


                      private getSliceEndPosition(flag: string): number
                      const flagPosition = this.flags.indexOf(flag) + 1;
                      return flagPosition < this.minObjectKeys
                      ? this.minObjectKeys
                      : flagPosition;



                      const fooLover = new MyClass();
                      alert(JSON.stringify(fooLover.buildBaseObject("d")));


                      Here is the demo






                      share|improve this answer





























                        1
















                        I also got inspired by the answer from @jack-bashford:



                        class MyClass 
                        private flags = [...Array(26)].map((_, i) => (i + 10).toString(36));
                        private minObjectKeys = 4;

                        public buildBaseObject(flag: string): any
                        return this.getFlagPortion(flag).reduce(
                        (obj, key) => ( ...obj, [key]: key === flag ),

                        );


                        private getFlagPortion(flag: string): string[]
                        const sliceEndPositon = this.getSliceEndPosition(flag);
                        return this.flags.slice(0, sliceEndPositon);


                        private getSliceEndPosition(flag: string): number
                        const flagPosition = this.flags.indexOf(flag) + 1;
                        return flagPosition < this.minObjectKeys
                        ? this.minObjectKeys
                        : flagPosition;



                        const fooLover = new MyClass();
                        alert(JSON.stringify(fooLover.buildBaseObject("d")));


                        Here is the demo






                        share|improve this answer



























                          1














                          1










                          1









                          I also got inspired by the answer from @jack-bashford:



                          class MyClass 
                          private flags = [...Array(26)].map((_, i) => (i + 10).toString(36));
                          private minObjectKeys = 4;

                          public buildBaseObject(flag: string): any
                          return this.getFlagPortion(flag).reduce(
                          (obj, key) => ( ...obj, [key]: key === flag ),

                          );


                          private getFlagPortion(flag: string): string[]
                          const sliceEndPositon = this.getSliceEndPosition(flag);
                          return this.flags.slice(0, sliceEndPositon);


                          private getSliceEndPosition(flag: string): number
                          const flagPosition = this.flags.indexOf(flag) + 1;
                          return flagPosition < this.minObjectKeys
                          ? this.minObjectKeys
                          : flagPosition;



                          const fooLover = new MyClass();
                          alert(JSON.stringify(fooLover.buildBaseObject("d")));


                          Here is the demo






                          share|improve this answer













                          I also got inspired by the answer from @jack-bashford:



                          class MyClass 
                          private flags = [...Array(26)].map((_, i) => (i + 10).toString(36));
                          private minObjectKeys = 4;

                          public buildBaseObject(flag: string): any
                          return this.getFlagPortion(flag).reduce(
                          (obj, key) => ( ...obj, [key]: key === flag ),

                          );


                          private getFlagPortion(flag: string): string[]
                          const sliceEndPositon = this.getSliceEndPosition(flag);
                          return this.flags.slice(0, sliceEndPositon);


                          private getSliceEndPosition(flag: string): number
                          const flagPosition = this.flags.indexOf(flag) + 1;
                          return flagPosition < this.minObjectKeys
                          ? this.minObjectKeys
                          : flagPosition;



                          const fooLover = new MyClass();
                          alert(JSON.stringify(fooLover.buildBaseObject("d")));


                          Here is the demo







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 28 at 21:54









                          Ali HabibzadehAli Habibzadeh

                          8,8612 gold badges43 silver badges66 bronze badges




                          8,8612 gold badges43 silver badges66 bronze badges































                              draft saved

                              draft discarded















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55395776%2frefactoring-javascript-typescript-eliminating-repeated-code-blocks%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                              155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해