Calculating the total price in React - javascript

So this is my first attempt with React.
I have to calculate the (total)price for a reservation.
The reservation price is determined by a few factors:
Length of the boat: €1,25 for every meter
The amount of people: €1 per person
Use of electricity: €1,25 a day
Let's say the boat is 10m long and 2 people are on there who use electricity. They stay for 2 days. The calculation would be like the following:
BoatLength(10) * 1.25 * 2 = 25
AmountOfPeople(2) * 1 * 2 = 4
UseOfElectricity(true) = 1.25 * 2 = 2.5
total_price = €25 + €4 + €2.5 = €21.5
I try to implement that in my code, which looks like this:
import React, { Component } from 'react'
import BoatForm from "./BoatForm";
import StayForm from "./StayForm";
export default class PriceCalculator extends Component {
/**
* So, we created a form for the customers so that they can register their boat.
* Now we want to let them know how much their reservation costs.
* The size of the boat, amount of people, amount of days and use of electricity are all parameters.
*/
constructor(props) {
super(props)
this.state = {
boat_length: '',
amount_of_people: '',
arrival_date: '',
leave_date: '',
use_of_electricity: '',
box_number: ''
}
}
/**
* We use date fields in our form to define the stay date of the customer.
* That means we have to calculate the days ourselves.
*/
calculateStayTime() {
const ArrivalDate = new Date(this.state.arrival_date);
const LeaveDate = new Date(this.state.leave_date);
// calculate difference
const DiffTime = Math.abs(LeaveDate - ArrivalDate);
const DiffDays = Math.ceil(DiffTime / (1000 * 60 * 60 * 24));
let AmountOfDays = DiffDays;
return AmountOfDays;
}
/**
* Prices per day:
* - Price per meter: 1,25
* - Price per person: 1
* - Price for using electricity: 1,25
*/
calculatePrice() {
const BoatLength = this.state.boat_length;
const meter_price = 1.25;
const Persons = this.state.amount_of_people;
const persons_price = 1;
let price_per_day = BoatLength * meter_price + Persons * persons_price;
const electricity_price = 1.25;
const use_of_electricity = true;
// ? = if statement
price_per_day = price_per_day + (use_of_electricity ? electricity_price : 0);
// const total_price = price_per_day * AmountOfDays;
}
}
I struggle with passing the variables from calculateStayTime() to calculatePrice(). Can anyone help me with how to formulate my calculation to React.JS?

You need to use the result of calculateStayTime inside calculatePrice. You can assign the stay time value to a variable but I'd probably just replace the last line: // const total_price = price_per_day * AmountOfDays; can be replaced with const total_price = price_per_day * this.calculateStayTime(); which should give you what you need.

Related

Override javascript

Drawing
when I hit the button on the top left on https://real-one.shifaul.repl.co/, nothing happens except the text changing to "to daily"
but what I want it is when I hit the button , it will change my javascript
the line that is running now (highlighted in blue) will stop working, and the line that is in the comment will start working, when I hit again it gets back to normal. it will go on forever
fetchTexts().then(([enQuotes, bnQuotes]) => {
const totalQuotes = enQuotes.length;
function getQuote() {
const pickedIndex = Math.floor(Math.random() * totalQuotes);
//const now = new Date(); const days = Math.floor(now/1000/60/60/24); const pickedIndex = days % totalQuotes
const newImageIndex = Math.floor(Math.random()*6); document.body.style.backgroundImage = `url(${newImageIndex}.jpg)`;
document.querySelector("#text1").innerText = enQuotes[pickedIndex];
document.querySelector("#text2").innerText = bnQuotes[pickedIndex];
}
getQuote(0);
setInterval(function() {
getQuote()
}, 24 * 60 * 60 * 1000);
});
full code: https://replit.com/join/xedbtvda-shifaul
I think that based on your code, you can do that:
var elem = document.getElementById("myButton1")
const now = new Date();
const days = Math.floor(now/1000/60/60/24);
const pickedIndex = elem.value === 'On refresh'
? Math.floor(Math.random() * totalQuotes)
: days % totalQuotes
This worked for me (I tested by lowering the value of getQuotes interval)

Re-selecting another value and clac but old result displays in JS

I'm studying calc. I'm having problem with re-selecting value and calc.
Here is my whole program
https://jsfiddle.net/diessses/c9ykmsf2/6/
When user select value then press submit. it works perfectly. However when user change such as 'cb_amount' , s_month and 's_year' Then click submit below code part displays OLD result. Other part result works fine. Could you teach me write code please?
// PAY_START_END_MONTH_FMT message
const PAY_START_END_MONTH_FMT = "If loan start Month is :start ,<br> Final loan paying will be :end ";
let s_month = document.getElementById(elementId.s_month).value;
if (s_month) {
let s_year = document.getElementById(elementId.s_year).value;
let date = new Date();
date.setMonth(s_month - 1);
date.setFullYear(s_year);
let startMonth = DateManager.formatDate(date, DateManager.getFormatString().YYYY_MM);
DateManager.addMonth(date, (years * 12) - 1);
let endMonth = DateManager.formatDate(date, DateManager.getFormatString().YYYY_MM);
document.getElementById("pay_start_end_month").innerHTML = PAY_START_END_MONTH_FMT.replace(":start", startMonth).replace(":end", endMonth);
}
// CB_SENTENCE_FMT message
const CB_SENTENCE_FMT = "Combined bonus amount will be :j_actual_cb_ttl. Paying times is :j_cbTimes . mothly paying is :j_monthly_bns_payment";
if (bSecondToLastTtl > 1) {
let j_actual_cb_ttl = ValueUtils.comma(bSecondToLastTtl);
let j_cbTimes = cbTimes;
let j_monthly_bns_payment = ValueUtils.comma(monthly_b);
document.getElementById("j_cb_sentence").innerHTML = CB_SENTENCE_FMT.replace(":j_actual_cb_ttl", j_actual_cb_ttl).replace(":j_cbTimes", j_cbTimes).replace(":j_monthly_bns_payment", j_monthly_bns_payment);
}
There are a lot of variables which you are have declaration as "const". Try changing those to "let". Read about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let. I have forked your code and tried, seems to be updating the data based on the new values.
Forked fiddle https://jsfiddle.net/b5g73x02/. Below is what I changed.
let cbTimes = years * 2; //
let diff = amount - downpayment;
let justDevideCbAmount = cb_amount / cbTimes;
let monthly_b = (Math.floor(justDevideCbAmount / 100) * 100);
let bSecondToLastTtl = monthly_b * cbTimes;
let paymentTimes = years * 12;
let interestMod = 10000 + (interest * 100);
let ttlWInterest = parseInt(((amount - downpayment) * interestMod )/ 10000);
let ttlWInterestNegativeCb = ttlWInterest - bSecondToLastTtl;
let jstDevideMonthly = ttlWInterestNegativeCb / paymentTimes;
let secondToLastMonthlyPayment = (Math.floor(jstDevideMonthly / 100) * 100);
let firstMonthlyPayment = ttlWInterestNegativeCb - (secondToLastMonthlyPayment * (paymentTimes - 1));
let jKinri = (interest / 100).toFixed(5);
let kinriFinal = ValueUtils.comma(parseInt(ttlWInterest - (amount - downpayment)));

Node.js optimization with constants

Please compare:
// Version 1
const oneHour = 60 * 60
function checkTime(timePast) {
if (timePast<7 * 24 * oneHour) {
// Do something
}
}
// Version 2
const oneHour = 60 * 60
const oneWeek = 7 * 24 * oneHour
function checkTime(timePast) {
if (timePast<oneWeek) {
// Do something
}
}
During millions of calls to checkTime(), is version 2 faster than version 1, or is Node.js smart enough to make the extra calculation in version 1 only once?
You can easily check it like this:
const oneHour = 60 * 60
const oneWeek = 7 * 24 * oneHour;
const randomData = generateArray();
function generateArray () {
let arr = [];
for(i = 0; i < 10000000; i++) {
arr.push(Math.floor(Math.random() * 10))
}
return arr;
}
function checkTime1(timePast) {
if (timePast<7 * 24 * oneHour) {
Math.random()
}
}
function checkTime2(timePast) {
if (timePast<oneWeek) {
Math.random()
}
}
console.time('checkTime1');
randomData.forEach(i => checkTime1(i))
console.timeEnd('checkTime1');
console.time('checkTime2');
randomData.forEach(i => checkTime2(i))
console.timeEnd('checkTime2');
After several checks change order of "checkTime2" and "checkTime1", to be sure the result is valid. Seems Node.js is smart enough to make the extra calculation.
According to this article: Node.js Under The Hood #10 - Compiler Optimizations! Node's compiler will perform Constant Folding optimization, such that const j = 3 + 9 will become const j = 12.

Vue Js - Calculation Criteria in Reverse

Am Having situation where i had to reverse a calculation criteria to make it clear :
i have sub_total field which is editable and user can change the value of it
first the pre tax is applied to this sub_total and give me pre_total
second the vato tax is applied to the sum of ( sub_total and pre_total ) and give me vato_total
third the tx tax is applied to the sub_total and give me tx_total
the final step is the grand total which is the sum of sub_total + pre_total + vato_total + tx_total .
and here is the demonstration code of the above steps :
let subtotal_with_ewa = Number((this.subtotal_price / 100) * this.unit.reservation.prices.ewa_parentage) + Number(this.subtotal_price);
this.total_ewa = parseFloat((this.subtotal_price / 100) * this.unit.reservation.prices.ewa_parentage).toFixed(2)
this.total_vat = parseFloat((subtotal_with_ewa / 100 ) * this.unit.reservation.prices.vat_parentage).toFixed(2);
this.total_ttx = parseFloat((this.subtotal_price / 100) * this.unit.reservation.prices.tourism_percentage).toFixed(2);
this.total_price = parseFloat(subtotal_with_ewa + Number(this.total_vat) + Number(this.total_tourism)).toFixed(2);
this.unit.reservation.prices.total_price_raw = parseFloat(subtotal_with_ewa + Number(this.total_vat) + Number(this.total_ttx) ).toFixed(2);
this.unit.reservation.prices.total_price = this.unit.reservation.prices.total_price_raw ;
this.total_price = this.unit.reservation.prices.total_price ;
this.unit.reservation.prices.price = this.subtotal_price
and it's working perfect as the following screen shot
now the question is : what do i do to make the whole operation as reverse i mean what i had to do if i changed the grand total value i need to re-calcuate those values till get the sub_total again .... any ideas ?
You need to make computed properties they will recompute any time a dependancy is changed, for example:
subtotal_with_ewa(){
return Number((this.subtotal_price / 100) *
this.unit.reservation.prices.ewa_parentage) + Number(this.subtotal_price);
}
You can use getters and setters with computed properties or separate them from the bound v-model on the fields.
The below functions should solve the problem.
the function accepts the percentage of each tax as argument and returns a json will all the values.
function fromSubTotal(subTotal, pre, vato, tx) {
const preAmount = subTotal * pre / 100
const vatoAmount = (subTotal + pre) * vato / 100
const txAmount = subTotal * tx / 100
const total = subTotal + preAmount + vatoAmount + txAmount
return {subTotal, preAmount, vatoAmount, txAmount, total}
}
function fromTotal(total, pre, vato, tx) {
const subTotal = (total * 100) / (100 + pre + tx + (1.01 * pre * vato))
return fromSubTotal(subTotal, pre, vato, tx)
}
// eg.
console.log(fromSubTotal(100,1,1,1))
console.log(fromTotal(103.01,1,1,1))

interchanging and manipulating two form input values

I've created a calculator that requires a value in either months or years in order to perform a calculation. The calculator works with one exception: It is required that the two input fields update based on the value of each other. here's an example of the behavior I am attempting to recreate:
https://www.bankrate.com/calculators/mortgages/loan-calculator.aspx
I apologize in advance if the following example reads poorly, but here it goes:
If a user enters 72 'months', the 'years' input will divide months by 12 and display the result. After doing a little tooling around, I found that using [a, b] = [b*12, a/12] gets me halfway there. The problem I'm running into is that once values have been entered, the value of the most recently updated input is updated with the previous value (including the calculation). For example, User enters 60 months > years is populated with the value of 5 > user changes months to a value of 72 > years is populated with a value of 6 > months is automatically populated with a value of 60 (years remains at a value of 6)
Here's the JS:
const loan = () => {
let principal = document.getElementById('principal')
let interestRate = document.getElementById('interestRate')
let terms = document.getElementById('terms')
let termsInYears = document.getElementById('termsInYears')
let payment = document.getElementById('payment')
let total = document.getElementById('total')
let totalInterest = document.getElementById('totalInterest')
let closingCosts = document.getElementById('closingCosts')
let netAfterFees = document.getElementById('netAfterFees')
let totalFeesAndInterest = document.getElementById('totalFeesAndInterest')
let trueCost = document.getElementById('trueCost')
let amount = parseFloat(principal.value)
let interest = parseFloat(interestRate.value) / 100 / 12
let payments = parseFloat(terms.value)
let fees = parseFloat(closingCosts.value)
if(!fees) {
closingCosts.value = 0
}
[terms.value, termsInYears.value] = [termsInYears.value*12, terms.value/12]
let x = Math.pow(1 + interest, payments)
let monthly = (amount * x * interest) / (x-1)
let totalPay = (monthly * payments)
if (isFinite(monthly) && payment) {
payment.innerHTML = monthly.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
netAfterFees.innerHTML = (amount - fees).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
total.innerHTML = (totalPay).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
totalInterest.innerHTML = ((monthly * payments) - amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
totalFeesAndInterest.innerHTML = (totalPay - amount + fees).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
trueCost.innerHTML = (((totalPay - amount + fees) / amount)*100).toFixed(2)
} else {
payment.innerHTML = '0'
netAfterFees.innerHTML = '0'
total.innerHTML = '0'
totalInterest.innerHTML = '0'
totalFeesAndInterest.innerHTML = '0'
trueCost.innerHTML = '0'
}
}
I can't speak on the quality of the working calculator given my experience level. However, it does work. I'm just having one heck of a time getting past this [likely silly] input exchange.
Any help would be greatly appreciated!
I ended up solving this issue using querySelector and then adding an event listener for each input:
document.querySelector('#terms').addEventListener('input', (e) => {
termsInYears.value = e.target.value / 12
})
document.querySelector('#termsInYears').addEventListener('input', (e) => {
terms.value = e.target.value * 12
})

Categories

Resources