Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have lot enough functions, which look like:
var functionName = function(e) {
//
};
where all the parameters are getting passed in in a single container e. Most times values are simple values (no functions), ex.:
{ parameter1: 1, parameter2: "Name", parameter3:{ subParameter1: "A"}}
But there're times when I pass in functions as in: { p2:function(){...} }
I have two options when it comes to utilising parameter values:
Options 1: get parameter values from the chain, starting from e: e.parameter1, e.parameter3.subParameter1 etc.
Option 2: use cached parameter values:
var parameter1 = e.parameter1;
var subParameter1 = e.parameter3.subParameter1;
The second option improves readability but increases the number of vars and the size of the code base. On another hand it's much drier when using long chains, i.e. e.p1.p2.p3 etc.
What reasoning should I use for choosing between those two options?
**Update 1 - the question sounds quite subjective, let me re-prase it.**
I don't mind using chains all the way, no local vars codebase is smaller, I can always figure out what's what, are the any cases when caching is a must?
A combination, based on depth(e.p1 vs e.p1.sp2.ssp3) and frequency of use. Deeper sub-properties and high usage of any sub-property both benefit from caching.
Nested property look ups can get costly, and caching the value after executing the look up once is valuable if you're going to use it a lot. This is only more efficient if you're accessing a particular property on the chain more than once, and the more you access it, the more you benefit from caching.
If you only have one level deep(e.p1, e.p2, e.p3) and you're only looking up each property value once, don't bother.
If you're accessing e.p1.sp2.ssp3 all throughout your function, cache it for sure.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
I am trying to create a javascript structure that looks like that:
[{'red': {color:'red},...}]
starting with an array of colors:
const COLORS = ['red','yellow']
This is what I have tried:
const finalArray = COLORS.map(color => ({ [color]: { color } }))
However this produces an array that looks like that:
[{red: {color:'red'}}]
instead of [{'red': {color:'red'}}]
Which is not the same and will prevent the library I am using from understanding the array.
Any idea is welcome.
I edited the question since there where some typos. Hope it’s clearer now.
Thanks
What are the differences between:
[{red: {color:'red'}}]
// and
[{'red': {color:'red'}}]
If it's only a quote related matters, you can do like:
COLORS.map(color => ({ [`'${color}'`]: { color } }));
These are just two ways of representing the same array/object. If you need a string containing the canonical representation of the array/object (with double quotes around the names of the properties), you can use JSON.stringify(finalArray).
Please note this will quote ALL your property names, like in:
[{"red":{"color":"red"}}]
And please note the above is a string, as if you did:
finalString = '[{"red":{"color":"red"}}]'
(Note: this question has been closed, and I agree it's not clear enough. But it's quite evident that the user is confusing the internal structure of an array/object with its external representation, and with the way the array/object is shown by a development environment, browser, etc. As this is a very common problem, mostly in new programmers or newcomers to a tool, the question and the answers may still be helpful.)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
I'm a huge fan of functional programming. I strive to use point free notation when I can. However, I often don't understand when point free notation is appropriate or when it is overkill. I typical delema that I run into is when I have a three or fewer functions that I would love to use a compose(...) statement for to avoid creating variables. However, I often feel like the code ends up looking uglier when I use compose(...) for such few functions compared to using intermediate variables.
Here's an example of my dilemma:
// Prefering point free notation
(address, signer, execute) =>
(atr, sequenceId) =>
compose(
setTxHash(atr, sequenceId),
execute(address, signer),
findTx,
)(atr, sequenceId);
// Preferring temporary variables
(address, signer, execute) =>
(atr, sequenceId) => {
const step1 = findTx(atr, sequenceId);
const step2 = execute(address, signer)(step1);
const step3 = setTxHash(atr, sequenceId)(step2);
return step3;
}
// function composition without using compose(...) method
(address, signer, execute) => (atr, sequenceId) =>
setTxHash(atr, sequenceId)(
execute(address, signer)(
findTx(atr, sequenceId)
)
)
I know asking "do any of these look better than others?" may be too subjective but are there any rules of thumb I can use or any good resources that talk about this and can offer a helpful perspective?
Thanks in advance!
If you need to introduce the points (variables with names) anyway because you're passing them to multiple functions, using compose is overkill. The third version of your function is the cleanest in that regard. Also, names are always useful if they are descriptive, since that aids the understandability of the code.
Only if you could write
(execute) => compose(
setTxHash,
execute,
findTx,
)
the usage of compose gains you anything (in particular, conciseness).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
selectAction: (actionEvent) => {
if (actionEvent instanceof Action1) {
// action1 body implementation
} else if (actionEvent instanceof Action2) {
// action2 body implementation
}
}
The above code snippet reflects that different types of action which does different functionalities.I have used if and else condition to check action.
I feel it's not a good solution since I might have more actions in the future and my if-else-ladder will keep growing and I need to update my code again when there is a change.
Any idea on improving this specific scenario?
Use the approach of duck typing to avoid conditional scenarios. Source
Have a method called selection() inside each type instance Action1 and Action2 so- on and use that to define the body/desired functionality you want to build. And simply call selection() method avoiding condition. So based on the instance of the type it will call the correct selection() method of the corresponding type
There's nothing inherently wrong with using if/else in TypeScript.
However, when you're using instanceof, the odds are that you probably have a better option available. In this case, almost certainly, the actions themselves should be responsible for doing what they do:
selectAction: (actionEvent) => {
actionEvent.execute();
}
...or
selectAction: (actionEvent) => {
const action = /*...derive action from actionEvent...*/;
action.execute();
}
...or similar (or of course, use actionEvent.execute() directly instead of selectAction).
This is fundamentaly polymorphism, having different objects conforming to the same interface, and doing (potentially) different things when called.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I did a little research, and the best answer I found is:
function overloading in js
Top 10 answers did gave me some hints and clues, but not the consistent way how to handle those situations in general.
Let's take a question a little further:
What if I am making API for someone else. That should give you the answer to following questions:
Why am I doing this?
JS doesn't have overriding in strict sense (yes I am aware, not the point)
Pass the object with optional parameters (Would prefer it, it's not up to me)
Specific solutions that assume types, fixed number of parameters, single values etc.
Some of the functions have to take many optional parameters (and some non-optional ones). So the function looks something like:
var f = function (unopt1, unopt2, op1, op2, op3) {
// code
}
The unoptX parameters are not optional.
The opX parameters are optional (in a sense they can be equal to 1 value from fixed set or values or not passed to function at all).
So function can be called in any of the following ways:
f("z", "b")
f("a", "b", 1, "ff");
f("a", "b", "ff", "hic");
f("a", "b", "ff", "no-hic");
etc.
Obviously, optional parameters each can have certain values, let's say they are listed in a certain order. And ofc. function behaves differently depending on the parameters
What would be your reccomended approach on this? Multiple ones are fine, prefferably you will point out what are ups/downs of certain approach over the other.
Use the spread operator as the argument:
function f(...args){
switch(args.length){
case 1:
get()
case 2:
set()
default:
setWithOptions()
}
}
Use an "options" object or ES6 "rest parameters"
var f = function (unopt1, unopt2, opts) {
opts = opts || {};
// later... if( opts.yourOptionalArg )
}
ES6 Rest Parameters
var f = function (unopt1, unopt2, ...args) {
console.log(args)
var firstOptionalArg = args[0];
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I've a question, not in how to do something but rather in the "standard" or "accepted" way.
Which of this is the preferred one, and why?
var data = {
employees:{
"John Williams":{
...
},
"Susane Rodgers":{
...
},
"Clint Eastwood":{
...
}
}
};
var data = {
employees:[
{
name:"John Williams",...
},
{
name:"Susane Rodgers",...
},
{
name:"Clint Eastwood",...
}
]
};
This is basically your data structure. The only thing that is "accepted" or preferred in data structures is simplicity. However many times it turns out that an API or old code has been written in a way that forces you to use a certain data structure. In your case, the first example suggests that there will not be employees with the same name, which is unacceptable since people with the same names exist and thus your application has a potential weakness. So the second example would be the better choice in that case.
Similar to the other answer, something else to consider about your data structure is how you plan on using the data. Depending on what your insertion / retrieval / removal / etc needs are, you may decide that one data structure is easier for you to use. Because you're using objects or arrays, you'll have access to different methods for you to manipulate your data structure.