how to bundle cases for "data-" attributes in a switch statement? - javascript

I'm running a switch statement with fairly many cases handling data-attributes.
Currently I'm stuck with this:
switch(attribute) {
case "value":
case "data-vv-validations":
case "data-relation":
case "data-tolerance":
case "data-theme":
case "type":
case "readonly":
case "size":
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
break;
}
I'm wondering if it's possible to combine all data- attributes into a single case, because listing all possible options I'm running into is kind of "not generic"...
Question:
In CSS selectors I can do somethink like [class*=" ui-icon-"]. Can I also make the case value more generic?
Thanks!

Sort of. You can see if the first characters are "data-, and if so, just use those chars for the switch.
var a = attribute.slice(0, 5) === "data-" ? "data-" : attribute;
switch(a) {
case "value": case "data-": case "type": case "readonly": case "size":
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
break;
}
This reduces all data- attributes to a single testable value. Note that you still use the full attribute with the setters[].
Or since you already seem to have the attribute names in a setters map, you could just do this:
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
Your switch seemed to be redundant since you were almost performing the same test when you do this:
if (setters[attribute]) {
Or if you need to test specifically the name, then...
if (setters.hasOwnProperty(attribute) && setters[attribute]) {

Simply solved with something like this:
var attributeSwitch = attribute.indexOf("data-") == 0 ? "data-*" : attribute;
case(attributeSwitch){
case "value":
case "data-*":
case "type":
case "readonly":
case "size":
if (setters[attribute]) {
element.setAttribute(attribute, setters[attribute]);
}
break;
}

No, you can't make "generic case statements".
But you can use an array of possible values and then check if the value is one of those.
function inArray(array, value) {
for(var i=0, len=array.length; i<len; i++) {
if(array[i] == value) {
return true;
}
}
return false;
}
var possibleValues = ["value",
"data-vv-validations",
"data-relation",
"data-tolerance",
"data-theme",
"type",
"readonly",
"size"];
if (setters[attribute] && inArray(possibleValues, attribute)) {
element.setAttribute(attribute, setters[attribute]);
}

Related

Javascript switch case keeps skipping to the default case

My Switch case keeps on going to default.
The condition is from the intersectionWord which outputs a specific keyword from an array which matches up to a word in the trigger word array aka an intersectionWord.
const TriggerWord = ["weather", "add", "multiply", "divide", "subtract", "hi", "hello",];
const intersectionWord = TriggerWord.filter(element => request.requestContent.includes(element));
And the objective was to pass that trigger word into the switch statement to evaluate if any of those cases match up. If they do match up it should output an alert. But currently it just seems to go straight to the default case every time.
I don't know where it is going wrong.
switch (intersectionWord) {
case TriggerWord[0].toString:
alert("Checking the weather");
break;
case TriggerWord[1].toString:
alert("Doing the math");
break;
case TriggerWord[2].toString:
alert("Doing multiplication");
break;
case TriggerWord[3].toString:
alert("Doing the division");
break;
case TriggerWord[4].toString:
alert("Doing the subtraction");
break;
case TriggerWord[5].toString:
alert("Just saying Hello");
break;
case TriggerWord[6].toString:
alert("Just saying Hello");
break;
default:
alert("I couldn't find a TriggerWord");
}
As noted in the comments, there are two problems with your code:
You're missing the () after .toString so it will call the function; also, it's not necessary to use .toString(), since they're already strings.
intersectionWord is an array, so it will never be equal to any of the strings in TriggerWords.
Instead of the switch/case statement, consider using an object:
const messages = {
weather: "Checking the weather",
add: "Doing the math",
multiply: "Doing multiplication",
...
}
Then you can loop over intersectionWords, looking up the corresponding message:
intersectionWords.forEach(word => alert(messages[word]))
Or you could combine them all into a single message:
let actions = intersectionWords.map(word => messages[word]).join(", ");
if (actions) {
alert(actions);
} else {
alert("No matching activity");
}

Switch statement to match several cases

I want to write a switch statement that will go through first 2 cases if they are both true. If not, only match the one that is true.
var vehicle = {main: false, detail: false};
switch(true) {
case (states.data.currentState.indexOf('main.vehicle') !== -1):
vehicle.main = true;
break;
case (states.data.currentState === 'main.vehicle.detail):
vehicle.detail = true;
break;
}
My problem is that after first break the switch statement ends and doesn't go to case 2. However if I remove break from first case it will jump to case 2 and apply vm.vehicle.detail = true; even though the case condition isn't met.
So if I remove break in the first case, my object will look like this anyway
{ main: true, detail: true }
If I don't it will look like this
{ main: true, detail: false }
How do I meet both conditions on single run of the switch?
Why not just take the comparisons as values for the object?
var vehicle = {
main: states.data.currentState.indexOf('main.vehicle') !== -1,
detail: states.data.currentState === main.vehicle.detail
};
ES6
var vehicle = {
main: states.data.currentState.includes('main.vehicle'),
detail: states.data.currentState === main.vehicle.detail
};

Switch statement not working within JSX (React.js)

I am trying to make my switch work within JSX, but for some reason it doesn't work.
Every output has an ID, which is I. Now I am trying to make a switch statement with I, but it will always return the default value.
Why?
My code:
{(() => {
switch (i) {
case "0": return "{indents}";
case "1": return "{indents2}";
case "2": return "{indents3}";
default: return "{indents3}";
}
})()}
This is all within a div with attribute key={i}.
I would recommend maps instead. Maps/objects are type insensitive. It will also reduce execution complexity:
const map = {
0: indents,
1: indents2,
2: indents3
}
<div>{map[i] || indents3}</div>
Alternatively, since you are using 0,1,2.., you can also have it as an array.
const map = [indents, indents2, indents3];
<div>{map[i] || indents3}</div>

How to simplify multiple if statements javascript?

I have multiple conditions to check. I have to add icons based on the conditions, Then I need to change the background color based on some other set of conditions. I am using if statement. This is my code.
JSON:
{
"date": "2017-05-12",
"a": false,
"b": true,
"c": true,
"d": false,
"status": "active"
}
Javascript:
if (date != -1) {
//do something
if (a) {
//Add icon a
}
if (b) {
//Add icon b
}
if (c) {
//Add icon c
}
if (d) {
//Add icon d
}
}
if(status == "active"){
//Background Green
}
else if (status == "onhold"){
//Background Yellow
}
else if (status == "inactive"){
//Background Red
}
else{
//Backgeound Grey
}
How do I simplify it?
The first half of you code looks fine.
For the second half of your code you should make use of a switch statement. These replace the if-else statements you are using and decide what to do when certain "cases" occur. For example:
switch(status) {
case 'active':
//background green
break;
case 'onhold':
//background yellow
break;
case 'inactive':
//background red
break;
default:
//background grey
break;
}
My idea is:
var icons = {
a: 'a.png',
b: 'b.png',
c: 'c.png',
d: 'd.png',
}
if (date != -1) {
Object.keys(icons).forEach(function(key) {
if (data[key]) {
//Add icon icons[key]
}
});
}
var statusColors = {
active: 'Green',
onhold: 'Yellow',
inactive: 'Grey',
}
//Background statusColors[status]
I think it is pretty good as it is. Is is better to have understandable code than complex code that does exactly the same thing.
You don't have to do
if (a === true)
as it's equivalent to
if ( a )
There is no way to "simplify" it, but you can try to use switch statement instead:
switch (status) {
case 'active':
// active
break;
case 'onhold':
// onhold
break;
case 'inactive':
// inactive
break;
default:
console.log('default');
}
You can even "group" some conditions:
switch (status) {
case 'active':
case 'onhold':
// active AND onhold case
break;
case 'inactive':
// inactive
break;
default:
console.log('default');
}
More about switch statement -> https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch
For Status variable you can use switch but for the first condition you have to use if-else statements I think.
switch (status) {
case "active":
//Background Green
break;
case "onhold":
//Background Yellow
break;
case "inactive":
//Background Red
break;
default:
//Backgeound Grey
}
a?setIconA():b?setIconB:c?setIconC;d?setIconD
and
status == "active" ? setGreen() : status == "onhold": setYellow()
and so on.
Your question doesn't quite give the details of the actions in each case, but if they're very similar, and there's a match between the property name and whatever action you need to take, you can use loops.
['a','b','c','d'].forEach(function (k)
{
if (objectFromJSON[k])
{
addIcon(k);
}
});
For the second part, it's slightly more complex as you have status names that don't match the color. You can either:
define CSS classes with those status names, and use the status name to set the class:
CSS:
.status-active
{
background: green;
}
.status-onhold
{
background: yellow;
}
.status-inactive
{
background: red;
}
JS:
theHTMLobject.classList.addClass('status-'+objectFromJSON.status);
use an object's properties (or a Map) to convert the status into a color
Do you mean "simplify" or do you mean "shorten" - because the two are almost mutually exclusive (shorter code is often not simpler!)
Your code is clear, and understandable. But it is a bit verbose, and can get much more complex as things grow. Sometimes it is better to shorten and the risk of making it a bit harder to understand.
You could consider things like a map between the status and the appropriate color
var backgroundStatusMap = {
"active":"green",
"onhold": "yellow",
"inactive": "red"
};
var backgroundColor = backgroundStatusMap[json.status];
Things like this can be added to easier if you as add new statuses - without having to trawl for the right place to put a new if.. condition.
Similarly, you could create a map for the booleans-to-icons
var iconMap = {
"a":"icon_a.png",
"b": "icon_b.png"
};
function getIcon(json, prop){
if(json[prop])
return iconMap[prop];
return null;
}
var iconA = getIcon(json,"a");
var iconB = getIcon(json,"b");

Why isn't my switch block (switching on $(e.target) .attr("class")) working?

I am trying to figure out why this code doesn't work..
All i want is to have simple event delegation to assign one event listener.
it only alerts, it doesn't animate.
Please let me know whats wrong here:
$(document).ready(function() {
var img = $("img");
$("span").click(function(e){
var targetClicked = $(e.target).attr('class');
//the alert works fine
alert(targetClicked)
switch(targetClicked){
// i deleted the rest of the cases
case d:img.stop(false,true);
break;
case e:img.slideDown().animate({"width":200, height:200, opacity:0.4,});
break;
//nothings works here as well
case f:alert("hi");
break;
}
});
});
What are d and e in your switch statement case conditions? The way you're code is written right now, they're being treated as variables and your code is probably blowing up with a "'d' is undefined" error.
If you want to switch on the class names "d" and "e", then you need to use the class names as strings:
switch (targetClicked) {
case "d":
//...
break;
case "e":
// ...
break;
}

Categories

Resources