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;
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
add a comment
|
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
add a comment
|
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
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
javascript typescript switch-statement refactoring
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
add a comment
|
add a comment
|
4 Answers
4
active
oldest
votes
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.
@jack ... which will work correctly ?
– Jonas Wilms
Mar 28 at 11:10
Sorry @JonasWilms - what wouldthisrefer to above? (I'm still not entirely clear about lexicalthis).
– Jack Bashford
Mar 28 at 11:11
@jack the samethisas insetFooTypeFlag
– Jonas Wilms
Mar 28 at 11:12
add a comment
|
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;
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 withthis.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 usefor(const flag of flags)but that is personal preference ...
– Jonas Wilms
Mar 28 at 11:08
1
@Lonely if there are properties other thana,b,c,d, they will also be set to boolean
– adiga
Mar 28 at 11:09
|
show 3 more comments
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
add a comment
|
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
add a comment
|
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
@jack ... which will work correctly ?
– Jonas Wilms
Mar 28 at 11:10
Sorry @JonasWilms - what wouldthisrefer to above? (I'm still not entirely clear about lexicalthis).
– Jack Bashford
Mar 28 at 11:11
@jack the samethisas insetFooTypeFlag
– Jonas Wilms
Mar 28 at 11:12
add a comment
|
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.
@jack ... which will work correctly ?
– Jonas Wilms
Mar 28 at 11:10
Sorry @JonasWilms - what wouldthisrefer to above? (I'm still not entirely clear about lexicalthis).
– Jack Bashford
Mar 28 at 11:11
@jack the samethisas insetFooTypeFlag
– Jonas Wilms
Mar 28 at 11:12
add a comment
|
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.
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.
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 wouldthisrefer to above? (I'm still not entirely clear about lexicalthis).
– Jack Bashford
Mar 28 at 11:11
@jack the samethisas insetFooTypeFlag
– Jonas Wilms
Mar 28 at 11:12
add a comment
|
@jack ... which will work correctly ?
– Jonas Wilms
Mar 28 at 11:10
Sorry @JonasWilms - what wouldthisrefer to above? (I'm still not entirely clear about lexicalthis).
– Jack Bashford
Mar 28 at 11:11
@jack the samethisas insetFooTypeFlag
– 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
add a comment
|
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;
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 withthis.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 usefor(const flag of flags)but that is personal preference ...
– Jonas Wilms
Mar 28 at 11:08
1
@Lonely if there are properties other thana,b,c,d, they will also be set to boolean
– adiga
Mar 28 at 11:09
|
show 3 more comments
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;
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 withthis.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 usefor(const flag of flags)but that is personal preference ...
– Jonas Wilms
Mar 28 at 11:08
1
@Lonely if there are properties other thana,b,c,d, they will also be set to boolean
– adiga
Mar 28 at 11:09
|
show 3 more comments
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;
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;
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 withthis.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 usefor(const flag of flags)but that is personal preference ...
– Jonas Wilms
Mar 28 at 11:08
1
@Lonely if there are properties other thana,b,c,d, they will also be set to boolean
– adiga
Mar 28 at 11:09
|
show 3 more comments
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 withthis.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 usefor(const flag of flags)but that is personal preference ...
– Jonas Wilms
Mar 28 at 11:08
1
@Lonely if there are properties other thana,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
|
show 3 more comments
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
add a comment
|
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
add a comment
|
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
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
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
add a comment
|
add a comment
|
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
add a comment
|
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
add a comment
|
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
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
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
add a comment
|
add a comment
|
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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