I'm trying to do a project for my CS assignment, but for some reason, it refuses to run the code correctly.
shake();
if (answers == 0 || 2 || 3 || 5) {
setProperty("screen1", "background-color", "green");
} else if (answers == 1 || 4) {
setProperty("screen1", "background-color", "red");
} else {
}
I set already set 'answers' to var answers = 0 and the shake function basically just randomizes a number for answers. However, even if answers == 1 or answers == 4, it still shows the background screen being green, not red. Any help?
Two solutions here worth exploring. One is to use a switch statement which is generally going to be the fastest:
function screenBg(answer) {
switch (answer) {
case 0:
case 2:
case 3:
case 5:
return 'green';
case 1:
case 4:
return 'red';
}
// In action:
setProperty("screen1", "background-color", screenBg(answers));
It can be a little weird to see a fall-through style of switch, which is why a look-up table is a good alternative:
const SCREEN_BG = [
'green', // 0
'red', // 1
'green', // 2
'green', // 3
'red', // 4
'green' // 5
];
setProperty("screen1", "background-color", SCREEN_BG[answers]);
Where here the correlation between index and colour should be pretty clear.
do it like this
shake();
if ([0,2,3,5].includes(answers)) {
setProperty("screen1", "background-color", "green");
} else if ([1,4].includes(answers)) {
setProperty("screen1", "background-color", "red");
} else {
}
the way your testing your if statement is wrong,
it should be like this:
if(answers === 0 || answers === 2 || ...)
Your conditions are incorrect and code can be improved a little bit.
let color = [0, 2, 3, 5].includes(answers)
? 'green'
: [1, 4].includes(answers)
? 'red'
: 'orange';
setProperty("screen1", "background-color", color);
If you prefer to use if-elseif-else
let color = "orange"; // this is for else block.
if ([0, 2, 3, 5].includes(answers)) color = "red";
if ([1, 4].includes(answers)) color = "green";
If "answers" is an array, use the condition like this:
[0, 2, 3, 5].some((x) => answers.includes(x))
Related
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));
}
}
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'));
I am having trouble with a basic task. I need to write a JavaScript program that contains an array of at least five strings, loops through the array, and calls a function for each item; this function should check to see how long the string is:
If the string is less than four characters, print the phrase "Less Than Four"
If equal to four characters, print "Exactly Four"
If longer than four, print "More Than Four"
I have tried so many things, but feel like I am looking in the wrong spots. I understand this is basic but I cant seem to wrap my head around this...
My Code right now:
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
var count;
for (count = 0; count < colors.length; count++) {
console.log(colors[count]);
}
if (colors > 4) {
console.log("greater than 4");
}
if (colors < 4) {
console.log("less than 4");
}
if (colors = 4) {
console.log("is equal to 4");
}
Arrays have built-in methods for looping that allow a callback function to be executed upon each iteration of the loop. In your scenario, since you are just needing to examine the string, the .forEach() method is probably the most appropriate.
In the function, you only need a simple if/then/else statement to determine which message to print.
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
colors.forEach(function(color){
if(color.length < 4){
console.log(color + " has less than 4 characters.");
} else if (color.length === 4) {
console.log(color + " has 4 characters.");
} else {
console.log(color + " has more than 4 characters.");
}
});
Newer versions of JavaScript support for..of syntax
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
for (const c of colors)
{ if (c.length > 4)
console.log(c, "greater than 4")
else if (c.length < 4)
console.log(c, "less than 4")
else
console.log(c, "equal to 4")
}
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
You should separate the concerns of the loop and the length check using a function -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = str =>
{ if (str.length > 4)
return "greater than 4"
else if (str.length < 4)
return "less than 4"
else
return "equal to 4"
}
for (const c of colors)
console.log(c, checkLength(c))
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
JavaScript is a multi-paradigm language, so it supports writing the same program in a wide variety of styles -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = str =>
{ if (str.length > 4)
console.log(`${str} is greater than 4`)
else if (str.length < 4)
console.log(`${str} is less than 4`)
else
console.log(`${str} is equal to 4`)
}
colors.forEach(checkLength)
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
JavaScript support for expressions is quite good too, removing the need for imperative-style keywords like if, else, switch, for, while, do and even return -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = x =>
x.length > 4 // if ...
? `${x} is greater than 4`
: x.length < 4 // else if ...
? `${x} is less than 4`
: `${x} is equal to 4` // else
console.log(colors.map(checkLength))
// [ "teal is equal to 4"
// , "violet is greater than 4"
// , "silver is greater than 4"
// , "green is greater than 4"
// , "red is less than 4"
// , "purple is greater than 4"
// ]
Call a function on every element and check the length inside an if-else block
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
var count;
for (count = 0; count < colors.length; count++) {
console.log(colors[count]);
stringLength(colors[count]);
}
function stringLength(string) {
if (string.length > 4) {
console.log("greater than 4");
} else if (string.length < 4) {
console.log("less than 4");
} else {
console.log("is equal to 4");
}
}
You need to put the if statements inside the curly braces of the for loop, so for every color it will run through all the if conditions and print if it matches.
A more idiomatic way of doing what you're currently trying to do is to implement the logic within the body of a forEach function, which is part of the Array object's prototype
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
colors.forEach(function(currentColorToCheck) { //currentColorToCheck is a temporary variable that the forEach function gives you (1 for every item of colors Array)
if (currentColorToCheck.length > 4) { // we use the .length function (part of String prototype and Array prototype) to get the length of the string
console.log("greater than 4");
}
if (currentColorToCheck.length < 4) {
console.log("less than 4");
}
if (currentColorToCheck.length === 4) { // here for an equality comparison, use === instead of =
console.log("is equal to 4");
}
})
The forEach is a more convenient way to express "Iterate over values of an Array". You can look at the documentation for some further guidance.
As a sidenote, there's tons of prototype (builtin) functions for every JavaScript type (Object, Array, String, Number, Date, Math, etc.) which you might want to study in your spare time. Mozilla Developer Network has great resources for that.
I have a JavaScript array like so:
const colors = ['blue', 'red', 'green'];
Given a number from 0 to Infinity, how can I find a color value like so:
colors[0] === 'blue';
colors[1] === 'red';
colors[2] === 'green';
colors[3] === 'blue';
colors[4] === 'red';
colors[5] === 'green';
// …
After the array is exhausted, finding colors based on a numerical value should loop through the array in order.
Given any number "x" between 0 and infinity:
colors[x % colors.length]
Will get you one of your colours
Seems like a fairly easy task to accomplish, all you have to do is to use modulo % operator when looking for a given index, as follows:
const colors = ['blue', 'red', 'green', 'pink', 'black', 'white', 'anyother'];
function getColor(idx){
return colors[idx % colors.length]
}
getColor(0) // "blue"
getColor(7) // "blue"
getColor(8) // "red"
getColor(13) // "anyother"
getColor(14) // "blue"
getColor(21) // "blue"
This way your array will stay intact and you won't get index higher than your array length.
Use the remainder (%) operator. This will give you the remainder of a division.
1/3 = 0 Remainder 3
1%3 = 3
12/3 = 4 Remainder 0
12%3 = 0
if num % 3 == 0
color = 'blue';
if num % 3 == 1
color = 'red';
if num % 3 == 2
color = 'green';
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.