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 1 year ago.
Improve this question
I am still a beginner to JS and I am kinda struggling on how to write multiple ifs in a correct way. For example I wrote something like this:
function calculatespot() {
//Spot 1 to 2 transfer bandage
if (spot1Selected == 1 && spot2Selected == 1) {
if (spot2Free == 1) {
localStorage.setItem('spot1Free', 1)
localStorage.setItem('spot2Free', 0)
localStorage.setItem('spot1Selected', 0)
localStorage.setItem('spot2Selected', 0)
document.getElementById('block1').style.backgroundColor = "#9eafa6"
document.getElementById('block2').style.backgroundColor = "#9eafa6"
if (user_item1 == "Bandage") {
localStorage.setItem("slot1Type", "")
localStorage.setItem("slot2Type", "Bandage")
document.getElementById('inventoryactionbtn').style.visibility = "Hidden"
document.getElementById('item1').src = "/static/images/transparant.png"
document.getElementById('item2').src = "/static/images/bandage.png"
localStorage.setItem('slot1Type', "")
localStorage.setItem('slot2Type', "Bandage")
}
}
}
This is not a very good way, but I still need all those points to match before executing the code. How could I write something like this in a better and more efficient way without having to nest all those ifs?
You can think about the following things to do:
reverse logic and return
separate logic in multiple functions
That will look like this. Which has the same functionality as your code, but less nested:
function setToSpot2Free() {
localStorage.setItem('spot1Free', 1)
localStorage.setItem('spot2Free', 0)
localStorage.setItem('spot1Selected', 0)
localStorage.setItem('spot2Selected', 0)
document.getElementById('block1').style.backgroundColor = "#9eafa6"
document.getElementById('block2').style.backgroundColor = "#9eafa6"
}
function setType2(type) {
localStorage.setItem("slot1Type", "")
localStorage.setItem("slot2Type", type)
document.getElementById('inventoryactionbtn').style.visibility = "Hidden"
document.getElementById('item1').src = "/static/images/transparant.png"
document.getElementById('item2').src = `/static/images/${type.toLowerCase()}.png`
}
function calculatespot() {
if (spot1Selected !== 1 || spot2Selected !== 1 || spot2Free !== 1) {
return;
}
setToSpot2Free();
if (user_item == 'Bandage') {
setType2(user_item);
}
}
Obviously there are more things iffy with your code, but you'll get there :)
A very important concept, at least to me, is the DRY principle. Which means, "Don't repeat yourself". If you are noticing that you are doing the same thing twice, with only a small difference in code, you can probably move this logic in its own function and set the "small difference(s)" as parameter(s) of that function.
Related
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 days ago.
The community is reviewing whether to reopen this question as of 4 days ago.
Improve this question
I'm asked to get attributes collection out of an array object,
let a = [
{name:'aname',age:21},
{name:'bname',age:22},
{name:'cname',age:23},
{name:'dname',age:24},
{name:'ename',age:25},
{name:'fname',age:26},
{name:'gname',age:27}]
// wanted
let ok = {
names:'aname;bname;cname;dname;ename;fname;gname',
ages:'21;22;23;24;25;26;27'
}
and I got 2 ways of doing it:
alpha just using map of an array:
// alpha
let res = {
names:'',
ages:''
}
res.names=a.map(iter=>iter.name).join(';')
res.ages=a.map(iter=>iter.age).join(';')
//then return res
// ========================================================
and beta just iterate the array and append each attribute in the tabulation array:
// beta
let res = {
names:[],
ages:[]
}
a.forEach(iter=>{
res.names.push(iter.name)
res.ages.push(iter.age)
})
// then handle res's fields
ok.names = res.names.join(';')
ok.ages = res.ages.join(';')
so which way should I use to get the collection? Will alpha get slower or faster than beta when the objects in a get lots of fields(attrs)?
Both approaches are good. I'd say it depends on your personal preference what you'd want to use.
However, It seems to me that if you are aiming for performance, the following would yield better results.
let a = [
{name:'aname',age:21},
{name:'bname',age:22},
{name:'cname',age:23},
{name:'dname',age:24},
{name:'ename',age:25},
{name:'fname',age:26},
{name:'gname',age:27}]
let ok = { names: '', ages: ''}
for (let i = 0; i < a.length; i++){
const iter = a[i]
ok.names += iter.name + ";";
ok.ages += iter.age + ";";
}
ok.names = ok.names.slice(0,-1)
ok.ages = ok.ages.slice(0,-1)
console.log(ok)
This apporach eliminates the need to create new arrays or joining them (join is a heavy operation). Just create the string you want and at the end of it all, remove the one extra semicolon.
I consider that alfa is simpler and clearer for me, but I guess it is up to you...
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
my code is not working at all
I need to solve this quiz
question is write convertToString as function !
this function should convert to string from parameter
ex )
let output = convertToString(120);
console.log(output); // --> '120'
let output2 = convertToString('hello');
console.log(output2); // --> 'hello'
let output3 = convertToString(true);
console.log(output3); // --> 'true'
this is what I wrote
function convertToString(anything) {
if (typeof anything === 'number' && typeof anything === 'boolean') {
let ret = anything.toString()
} else {
return anything;
}
return ret1;
}
convertToString(120);
The easiest way to convert anything is by making + operation with ""
function convertToString(anything) {
return "" + anything
}
console.log(convertToString(12));
console.log(convertToString(true));
console.log(convertToString('hello'));
console.log(convertToString(null));
console.log(convertToString(undefined));
Zero checks necessary.
function convertToString(val) {
return String(val);
// or return val.toString();
// or return '' + val;
}
console.log(convertToString(12));
console.log(convertToString(true));
console.log(convertToString('hello'));
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
I try to learn to write functional programming code in react.
could you check and review my code and say to me is it functional or not? or how can I write it better!
Thank you very much
oprationButton(val , oprator){
if(oprator === 'min')
return this.setState({currentVal: min(val)})
else if(oprator === 'plus')
return this.setState({currentVal: plus(val)})
function min(val){
if (val > 0)
return val
else return 0
}
function plus(val){
return val + 1
}
}
<button type="button"
onClick={() => this.oprationButton(this.state.currentVal,'min')}>Click Me!</button>
you can change your code like this
pluseButton(val, oprator) {
if (oprator === 'min') {
let min = this.mines(val)
return this.setState({currentVal: min})
} else if (oprator === 'plus')
return this.setState({currentVal: ++val})
}
mines(val) {
let sum = val - 1;
if (sum > 0) return sum
else return 0
}
<button type="button"
onClick={() => this.oprationButton(this.state.currentVal,'min')}>Click Me!</button>
I hope this code help u
Since oprationButton is mutating the state, which is not an internal variable, and is not returning anything, therefore it is not a pure function and it's not functional programming.
On the other hand, your internal functions plus and min are pure and could be said to be in a functional programming approach.
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 4 years ago.
Improve this question
I am trying to figure out how I can create a "game" where I have three dices, and three bets. If any of the bets hits, I will be granted 1 point, else nothing happens.
Example variables and arrays I would like to use;
var points = 1;
var slot1 = Math.floor((Math.random()*6)+1);
var slot2 = Math.floor((Math.random()*6)+1);
var slot3 = Math.floor((Math.random()*6)+1);
var dices = [slot1, slot2, slot3];
function Bet(bet1, bet2, bet3) {
"NEED HELP WITH THE CODE HERE"
}
Bet(1,2,3);
Thanks alot for all kinds of help!
I think a nudge in the right direction is more appropriate than a ready-to-go answer, since your question smells a little bit like homework :-)
You basically need to cross-check each item from both lists. You can do this with either a nested for .. in loop or a call to .some() with a nested .contains(). The latter will give you the cleanest solution. Docs
Alternatively, you can use Tagas' solution but that would make your function less reusable. If the number of bets vary, you'll need to adjust your function..
Try this:
function rollDice() {
//generate a number between 1 to 6
return Math.floor(Math.random() * (6 - 1 + 1)) + 1;
}
function makeBet(bet1, bet2, bet3) {
let slot1 = rollDice(),
slot2 = rollDice(),
slot3 = rollDice();
console.log('Slot 1:', slot1);
console.log('Slot 2:', slot2);
console.log('Slot 3:', slot3);
if(bet1 == slot1 || bet2 == slot2 || bet3 == slot3) {
//return 1 point as there is a match
return 1;
}
//return nothing as there was no match
return 0;
}
//Make a bet!
makeBet(1, 2, 3);
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
What would be the best way to format this code?
It looks a bit messy to me, in regard to indentation, etc.
if (typeof _srwc != 'undefined') {
for (var i=0; i < _srwc.length; i++){
var currentArg = _srwc[i];;
if (typeof window[currentArg[0]] == 'function') {
window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
} else {
console.log('The Setter method: "' + currentArg[0] + '" is undefined');
}
}
}
Try indenting the code inside the if, like this:
if (typeof _srwc != 'undefined') {
for (var i = 0; i < _srwc.length; i++) {
var currentArg = _srwc[i];;
if (typeof window[currentArg[0]] == 'function') {
window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
} else {
console.log('The Setter method: "' + currentArg[0] + '" is undefined');
}
}
}
Also, JSBeautifier is very useful for indenting JavaScript.
You can also use:
if (typeof _srwc != 'undefined')
{
for (var i = 0; i < _srwc.length; i++)
{
var currentArg = _srwc[i];
if (typeof window[currentArg[0]] == 'function')
{
window[currentArg[0]](currentArg[1], currentArg[2], currentArg[3]);
}
else
{
console.log('The Setter method: "' + currentArg[0] + '" is undefined');
}
}
}
That way all opening brackets are on the same vertical line as the closing ones and you can easily track which closing bracket is the one for a selected opening one (the first one below it on the same spacing distance). It's easier to trask the code that way if you're not using an IDE that is coloring the coresponding brackets.
When coding any language, normally entering a new block would cause indentation and exiting the same block does the opposite. (JS indentation should be 4 spaces)
ie
function xyz(){
alert("xyz");
}
and
function abc(){
if(true){
alert("true");
}else{
alert("false");
}
alert("abc");
}
..but like me if you get lazy and stop indenting using a tool like JSBeautifier whcih are available in most languages online just give it a search.