Review my code Funcational Programing in React [closed] - javascript

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.

Related

Js how to write multiple ifs in a efficient way? [closed]

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.

I need to sort it out this quiz [closed]

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'));

I want to create a little test-program with "dices" with javascript [closed]

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);

Test the return value of my function correctly at the time of return [closed]

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 years ago.
Improve this question
I can not test the return value of my function correctly at the time of return.
My exercise is this: I must compare two arrays and return true if they have at least one identical element but I need some assistance in figuring out what is wrong with my code:
function duplicateElements(m, n){
function test (element){
return n.includes(element);
}
return m.filter(test) != [] ? true:false;
}
You have to test the length property of the return value.
function duplicateElements(m, n) {
function test(element) {
return n.includes(element);
}
return m.filter(test).length > 0 ? true : false;
}

Javascript variable returning blank [closed]

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 8 years ago.
Improve this question
I am testing this code:
var thecol = '';
// Note: I know that value.cat = '3'
if (value.cat === '1') {
thecol = 'cat1';
} else if (value.cat === '2') {
thecol = 'cat2';
} else if (value.cat === '3') {
thecol = 'cat3';
} else if (value.cat === '4') {
thecol = 'cat4';
} else if (value.cat === '5') {
thecol = 'cat5';
};
alert(thecol);
The alert is blank for some reason.
Any ideas why.
Are you sure that value.cat is '3' and not 3? You can easily find out by logging typeof value.cat. Since you are using the deep equal it will only return true if both, the value and the type are the same:
'3' === 3 // -> false
'3' == 3 // -> true

Categories