How do Switch statement work with Symbols? - javascript

I'm new to JavaScript. Excuse if stupid question.
The following snippet makes sense. Nothing out of the ordinary:
const RED = 'red';
const ORANGE = 'orange';
const YELLOW = 'yellow';
const BLUE = 'blue';
const cat = 'blue';
function getThreatLevel(color){
switch(color){
case RED:
return 'severe';
case ORANGE:
return 'high';
case YELLOW:
return 'elevated';
case BLUE:
return 'low';
default:
console.log("I DON'T KNOW THAT COLOR!")
}
}
getThreatLevel(BLUE) = 'low'
getThreatLevel(cat) = 'low'
However, when changing the type of the first 4 variables to Symbols:
const RED = Symbol('red');
const ORANGE = Symbol('orange');
const YELLOW = Symbol('yellow');
const BLUE = Symbol('blue');
const cat = 'blue';
function getThreatLevel(color){
switch(color){
case RED:
return 'severe';
case ORANGE:
return 'high';
case YELLOW:
return 'elevated';
case BLUE:
return 'low';
default:
console.log("I DON'T KNOW THAT COLOR!")
}
}
getThreatLevel(BLUE) = 'low'
getThreatLevel(cat) = 'I DON'T KNOW THAT COLOR!'
Why does cat no longer return 'low'?

In the first example, cat and BLUE hold the same value, the immutable string "blue".
In the second example, cat and BLUE hold different values.
As an aside, each call to Symbol produces a unique value. So two different Symbols with the same description (which is only for debugging purposes) are different.
console.log('blue' === 'blue');
console.log(Symbol('blue') === 'blue');
console.log(Symbol('blue') === Symbol('blue'));

Related

Loop random numbers for a switch case up to n times

i´m getting crazy with this...I need to loop 10 times (automaticaly) a random number between 1-4 (both included), and this numbers must obtain a colour from switch cases', printed in the console.I tried to separate the switch cases, random function & the loop of that random function but....Any suggest???
//colours to assiged(depending on random number)
function getColor(colorNumber=0)
{
colorNumber = parseInt(colorNumber);
switch(colorNumber){
case 1: return "red";
break;
case 2: return "yellow";
break;
case 3: return "blue";
break;
case 4: return "green";
break;
default: return "black";
break;
}
}
//var with random generated
function getAllStudentColors(){
var getAllStudentColors = Math.floor(Math.random(4-1)*10) + 1;
}
//looping for function of random numbers
function loop() {
var exampleColor = 0;
while (exampleColor = 1) {
getAllStudentColors();
exampleColor++;
}
}
var exampleColor = getColor();
getAllStudentColors();
You could take a loop function with paramters for the count of loops and the function which should be called for every iteration and collect the result in an array.
I simplified the getColor fuunction by using an array and a fefault value for handing over an unknown property.
//colours to assiged(depending on random number)
function getColor(colorNumber = 0) {
return ["black", "red", "yellow", "blue", "green"][colorNumber] || "black";
}
//var with random generated
function getRandomColor() {
return getColor(Math.floor(Math.random() * 5));
}
//looping for function of random numbers
function loop(n, fn) {
let colors = [];
while (n--) colors.push(fn());
return colors;
}
console.log(...loop(10, getRandomColor));

TwilioQuest - The Ducktypium Classess JavaScript

I was just trying to complete a challenge on https://www.twilio.com/quest.
The questions in this game are:
The Ducktypium Classess
In your code folder, create a file named ducktypium.js. Inside of it, create a class called Ducktypium. The constructor should take a single string argument, a crystal color, and store that data in an instance variable named color. The color can only be red, blue, or yellow. The constructor should throw an error if the argument is any other string.
When the class is created, it should also define a property called calibrationSequence that is initally set to be an empty array.
The Ducktypium class must implement two instance methods: refract and calibrate. Each of these functions will be described below.
The Refract Method
One of the required methods describes the refractive properties of ducktypium when it is exposed to colored light.
The refract method must take a single string argument, which must be one of red, blue, or yellow. The method should throw an error if the argument is any other string, just like the constructor. This function should return a single string, which is the color produced by the combination of the instance's color property and the color passed in to the refract function.
If the instance's color property is the same as the argument passed in, return that value
If the combination of colors is different, it should return a string which is the combination of those two primary colors.
For reference, primary colors combine in the following ways:
red + blue = purple
red + yellow = orange
yellow + blue = green
The Calibrate Method
The other required method creates a calibration sequence required to stabilize a ducktypium crystal.
The calibrate method takes a single argument, an array of numbers. With this input array, you must do the following:
Sort the numbers from smallest to largest
Multiply each number in the array by 3
Assign the resulting array to the Ducktypium instance's calibrationSequencevariable.
My Code
const VALID_COLORS = ["red", "yellow", "blue"];
class Ducktypium {
constructor(color) {
if (!VALID_COLORS.includes(color)) {
throw new TypeError("Color must be red, yellow, or blue!");
}
this.color = color;
this.calibrationSequence = [];
}
refract(pickColor) {
if (!VALID_COLORS.includes(pickColor)) {
throw new TypeError("Color must be red, yellow, or blue!");
} else if (this.color == "red" && pickColor == "blue") {
return "purple";
} else if (this.color == "red" && pickColor == "yellow") {
return "orange";
} else if (this.color == "yellow" && pickColor == "blue") {
return "green";
} else {
return this.color;
}
}
calibrate(arrayOfNumber) {
let currentArray = arrayOfNumber.sort();
currentArray.forEach(item => {
let multiply = item * 3;
this.calibrationSequence.push(multiply);
});
}
}
try {
const badColor = new Ducktypium('pink');
} catch(e) {
console.log('Color must be red, yellow, or blue!');
}
const dt = new Ducktypium('red');
console.log(dt.color); // prints 'red'
console.log(dt.refract('blue')); // prints 'purple'
console.log(dt.refract('red')); // prints 'red'
dt.calibrate([3, 5, 1]);
console.log(dt.calibrationSequence); // prints [3, 9, 15]
The code I wrote runs perfectly, according to the game's question. But when submitted it always appears like this:
The refract method should return the color you get when its "color" property is concatenated with other primary colors. Look at the color combinations in the "Purpose" tab.
Even if I didn't use try / catch, can anyone see where I went wrong?
Thanks
You have not accounted for all combinations in the refract method. You've only done eg blue+red but not red+blue.
Can I suggest you write 3 boolean methods like
const mixPurple = (a,b) => (a == 'red' && b == 'blue') || (a == 'blue' && b == 'red');
const mixOrange = (a,b) => ...;
const mixGreen = (a,b) => ...;
And then your code does stay fairly similar
refract(pickColor) {
if (!VALID_COLORS.includes(pickColor)) {
throw new TypeError("Color must be red, yellow, or blue!");
} else if (mixPurple(this.color,pickColor)) {
return "purple";
} else if (mixOrange(this.color,pickColor)) {
return "orange";
} else if (mixGreen(this.color,pickColor)) {
return "green";
} else {
return this.color;
}
}
As it reduces all the combinations to just 3 branches and is easy to read
Just added another OR and it passed
refract(refColor){
if (this.color==="red" && refColor === "blue" || this.color==="blue" && refColor === "red"){
return "purple"
} else if (this.color==="red" && refColor === "yellow" || this.color==="yellow" && refColor === "red"){
return "orange"
} else if (this.color==="yellow" && refColor === "blue" || this.color==="blue" && refColor === "yellow"){
return "green"
} else if (this.color===refColor){
return this.color}
}
This might be a better and clean solution to the question without doing too much if-else.
class Ducktypium {
constructor(color) {
this.checkColor(color);
this.color = color;
this.calibrationSequence = [];
}
checkColor(color) {
if (!["red", "blue", "yellow"].includes(color)) {
throw new Error("Color must be red, yellow, or blue!");
}
}
combinations(colors) {
if (colors.includes("red") && colors.includes("blue")) return "purple";
if (colors.includes("red") && colors.includes("yellow")) return "orange";
if (colors.includes("yellow") && colors.includes("blue")) return "green";
}
refract(color) {
this.checkColor(color);
if (this.color === color) return color;
return this.combinations([this.color, color]);
}
calibrate(nums) {
this.calibrationSequence = nums
.map((num) => num * 3)
.sort((a, b) => (a < b ? -1 : 1));
}
}

How can I cast a string to an enum in Typescript

Enum definition:
enum Colors {
Red = "red",
Blue = "blue"
}
How can I cast some arbitrary sting (e.g. a result from a GET request) to the enum?
const color: Colors = "blue"; // Gives an error
In addition, why do integer enums work but string enums fail to have the same behavior?
enum Colors {
Red = 1,
Blue
}
const color: Colors = 1; // Works
If you are sure that the strings will always correspond to an item in the enum, it should be alright to cast it:
enum Colors {
Red = "red",
Blue = "blue",
}
const color: Colors = <Colors> "blue";
It won't catch the cases where the string is not valid. You would have to do the check at runtime:
let colorName: string = "blue"; // from somewhere else
let color: Colors;
if (Object.values(Colors).some((col: string) => col === colorName))
color = <Colors> colorName;
else
// throw Exception or set default...

Reduce the number of if query in jQuery

In my website user can enter two input . Input1 and Input2 .
So i have to calculate difference with these two number .
difference =input1-input2
so if the difference is greater than 700 i have to apply color red Please see the follow.
dIFFERENCE > 700 = red
dIFFERENCE > 800 = blue
dIFFERENCE > 900 = green
dIFFERENCE > 1000 = white
dIFFERENCE > 1100 = yellow
dIFFERENCE > 1200 = orange
dIFFERENCE > 1300 = purple
etc.. UP TO dIFFERENCE > 5000 = other color
So here i am writing the following jquery ,
var difference= $(".input1")-$(".input2");
if(difference>700){
$(".result").css("color","red");
}
if(difference>800){
$(".result").css("color","blue");
}
etc
is there any easy way to reduce this query ? Like i can store the color in an array and based on the difference i can fetch the result etc .
Please help
EDIT
What i tried is
var difference= $(".input1")-$(".input2");
if(difference >700 && difference<=800){
difference=700;
}else if(difference>=800 && difference<=900 ){
difference=800;
}else if(difference>=900 && difference<=1000 ){
difference=900;
}else if(difference>=1000 && difference<=1100 ){
difference=1000;
}
...
else if(difference>=4900 && difference<=5000 ){
difference=4900;
}
var differnce_array =[];
difference_array[700]="red";
difference_array[800]="blue";
difference_array[900]="green";
difference_array[1000]="white";
etc...
Still it is too much query . So please help to optimize this code
In this case i would create a dictionary, where the keys represent the thresholds and round the difference down to hundreds and look that key up in the dictionary:
var diff = 789; // your value
var diffs = {700: 'red', 800: 'blue', 900: 'green'}; //etc
var diffcol = Math.floor(diff/100)*100; //Floor down to hundreds
if(diffcol in diffs) console.log(diffs[diffcol]); //Validation
1ST APPROACH
You use a hashtable, it's a little bit like a hashset in c# or java, you just pair the keys to the values:
var hash = {
700:"red",
800:"blue",
900:"green",
//etc...
};
And this is how you can get your color:
var difference= $(".input1")-$(".input2");
roundedDifference = Math.floor(difference/100)*100
var color = hash[roundedDifference];
//This will be your color
2ND APPROACH:
You can round the number so you only get the hundereds i.e. 100,200,300,400,etc.
then you can use a switch statement:
var difference= $(".input1")-$(".input2");
roundedDifference = Math.floor(difference/100)*100
switch(roundedDifference) {
case 700:
$(".result").css("color","red");
break;
case 800:
$(".result").css("color","blue");
break;
case 900:
$(".result").css("color","green");
break;
case 1000:
$(".result").css("color","white");
break;
case 1100:
$(".result").css("color","yellow");
break;
case 1200:
$(".result").css("color","orange");
break;
case 1300:
$(".result").css("color","purple");
break;
case ... until 5000
break;
default:
console.log("difference not within range of 700-5000"
}
You can do this up to 5000.
Here is a working code for you:
function submit() {
var difference = $(".input1").val() - $(".input2").val();
console.log(difference)
function getColor() {
var color;
switch (difference) {
case 700:
color = "red";
break;
case 800:
color = "blue";
break;
case 900:
color = "green";
break;
case 1000:
color = "white";
break;
case 1100:
color = "yellow";
break;
case 1200:
color = "orange";
break;
case 1300:
color = "purple";
break;
default:
color = "magenta"
}
return color
}
$(".result").css("color", getColor(difference));
$(".result").html("The color is: "+ getColor(difference));
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" class="input1" placeholder="input1">
<input type="text" class="input2" placeholder="input2">
<button onclick="submit()">Difference</button>
<div class="result"> This changes color</div>
</body>
</html>
Please run the above snippet
Here is a working DEMO

How to alter CSS styles with Javascript?

I have an Array like this:
var colors = {
1: '#FFFF00',
2: '#FF0000',
3: '#80FF00',
4: '#00FFFF',
5: '#FF00FF'
};
And Javascript like this:
var color = Math.floor(Math.random()*5)+1;
if(color == document.getElementById('awards').style.borderColor) {
var color = Math.floor(Math.random()*5)+1;
}
else {
document.getElementById('awards').style.borderColor = color;
}
But my Javascript isn't working.
You are generating an index, but not subscripting the array.
jsFiddle.
Also, to nitpick, {} creates an object with properties, technically not an Array (though an Array is an object). [] is the literal notation for an Array in JavaScript.
Update
Here is maybe how I'd have written it, if that helps...
var getRandomColor = function() {
var colors = [
'#FFFF00',
'#FF0000',
'#80FF00',
'#00FFFF',
'#FF00FF'
];
return colors[Math.floor(Math.random() * colors.length) + 1];
}
var color = getRandomColor(),
element = document.getElementById('awards'),
borderColor = element.style.borderColor;
if (color == borderColor) {
color = getRandomColor();
}
else {
element.style.borderColor = color;
}
jsFiddle.
You are not really getting the random color, just getting the random number in a range, you'll need to change your code to this:
var color = colors[(Math.floor(Math.random() * 5) + 1).toString()];
if(color == document.getElementById('awards').style.borderColor) {
var color = colors[(Math.floor(Math.random() * 5) + 1).toString()];
}
else {
document.getElementById('awards').style.borderColor = color;
}
If you want to write dynamic CSS and write some code and logic inside, I recommend to take a look at http://www.dotlesscss.org/
I know it will take time to learn, but I proffered to mention about it, may be it help someone.

Categories

Resources