I have a problem where the babysitter earns different rates depending on times:
The babysitter
- starts no earlier than 5:00PM
- leaves no later than 4:00AM
- gets paid $12/hour from start-time to bedtime
- gets paid $8/hour from bedtime to midnight
- gets paid $16/hour from midnight to end of job
- gets paid for full hours (no fractional hours)
I'm wondering why I'm getting undefined when I pass through times in this function?
function calculatePay (startTime, bedTime, endTime){
function formatTime(time){
if (time.indexOf('00') === -1){
time = Number(time.split(":").shift()) + 1;
} else {
time = Number(time.split(":").shift());
}
if (time < 5) {
time = time + 12;
}
return time;
};
var start = formatTime(startTime);
var bedtime = formatTime(bedTime);
var end = formatTime(endTime);
var scheduleRange = {
start: 5,
lateNight: 12,
end: 16,
}
var payrate = {
beforeBed: 12,
sleeping: 8,
afterMidnight: 16
}
var calculateBeforeBed = function (start, bedtime) {
if (bedtime > start && bedtime <= scheduleRange.lateNight){
var beforeBedEarned = (bedtime - start) * payrate.beforeBed;
return beforeBedEarned;
} else if (bedtime > scheduleRange.lateNight) {
var beforeBedEarned = (scheduleRange.lateNight - start) * payrate.beforeBed;
return beforeBedEarned;
} else {
return 0;
}
};
var calculateAfterBed = function (start, bedtime, end) {
if (bedtime > start && bedtime <= scheduleRange.lateNight && bedtime <= end) {
var afterBedEarned = (scheduleRange.lateNight - bedtime) * payrate.sleeping;
return afterBedEarned;
} else if (bedtime <= start && end <= scheduleRange.lateNight){
afterBedEarned = (end - start) * payrate.sleeping;
return afterBedEarned;
} else if (bedtime <= start && end > scheduleRange.lateNight){
afterBedEarned = (scheduleRange.lateNight - start) * payrate.sleeping;
return afterBedEarned;
}
else {
return 0;
}
};
var calculateAfterMidnight = function (start, end) {
if (end > scheduleRange.lateNight && start <= scheduleRange.lateNight) {
var lateNightEarned = (end - scheduleRange.lateNight) * payrate.afterMidnight;
return lateNightEarned;
} else if (end > scheduleRange.lateNight && start > scheduleRange.lateNight) {
lateNightEarned = (end - start) * payrate.afterMidnight;
return lateNightEarned;
} else {
return 0;
}
};
function finalInvoice (start, bedtime, end){
if(start >= scheduleRange.start && end <= scheduleRange.end){
var pay = calculateBeforeBed(start, bedtime) + calculateAfterBed(start, bedtime, end)+ calculateAfterMidnight(start, end);
return pay;
};
};
}
calculatePay("7:00", "10:00", "1:00");
because your function has no return statement
function voidsum(a, b, c) {
var result = a + b + c;
}
function sum(a, b, c) {
var result = a + b + c;
return result;
}
console.log('voidfn', voidsum(123, 321, 231));
console.log('sum', sum(123, 321, 231));
Related
How to convert a time string like 1m15s to 75s, 75 or 75000 ideally using momentjs.
I attempted to parse that string using new Date('1m1s') but it gives Invalid Date.
I don't want to resort to regex:
const second = (function () {
const countdownStep = '1h1m1s'.match(
/(?:(?<h>\d{0,2})h)?(?:(?<m>\d{0,2})m)?(?:(?<s>\d{0,2})s)?/i
);
return (
(countdownStep.groups.h
? parseInt(countdownStep.groups.h) * 3600
: 0) +
(countdownStep.groups.m
? parseInt(countdownStep.groups.m) * 60
: 0) +
(countdownStep.groups.s ? parseInt(countdownStep.groups.s) : 0)
);
})();
You can use the duration interface of momentjs:
let s = '1m15s';
// convert to duration format and pass to momentjs
let secs = moment.duration('PT' + s.toUpperCase()).as("seconds");
console.log("seconds: ", secs);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Without library, it could be:
const unit = { s: 1, m: 60, h: 60*60 };
let s = '1m15s';
let secs = s.toLowerCase().match(/\d+./g)
.reduce((acc, p) => acc + parseInt(p) * unit[p.at(-1)], 0);
console.log("seconds: ", secs);
Another approach using plain js:
const getSecondsFromString = (str) => {
const hourIndex = str.indexOf("h")
const minuteIndex = str.indexOf("m")
const secondIndex = str.indexOf("s")
let hours = 0
let minutes = 0
let seconds = 0
if (hourIndex !== -1) {
hours = Number(str.substring(0, hourIndex))
}
if (minuteIndex !== -1) {
if (hourIndex !== -1) {
minutes = Number(str.substring(hourIndex + 1, minuteIndex))
} else {
minutes = Number(str.substring(0, minuteIndex))
}
}
if (secondIndex !== -1) {
if (minuteIndex !== -1) {
seconds = Number(str.substring(minuteIndex + 1, secondIndex))
} else if (hourIndex !== -1) {
seconds = Number(str.substring(hourIndex + 1, secondIndex))
} else {
seconds = Number(str.substring(0, secondIndex))
}
}
return hours * 3600 + minutes * 60 + seconds
}
Another approach without substring/replace, in O(n);
const getSecondsFromTimeString = (timeString) => {
let numberBeforeNextChar = 0;
let seconds = 0;
const symbolToSecondMap = {
"s" : 1,
"m" : 60,
"h" : 60*60,
"d" : 60*60*24
};
for (let i = 0; i < timeString.length; i++) {
let char = timeString.charAt(i);
if((+ char) <= 9 && (+ char) >= 0 ){
numberBeforeNextChar = (numberBeforeNextChar * 10) + parseInt(char);
continue;
}
if(char.toLowerCase() == char.toUpperCase()){
throw "Non alphanumeric symbol encountered";
}
if(symbolToSecondMap[char] === undefined){
throw "Invalid date alphabet encountered";
}
seconds = seconds + (numberBeforeNextChar * symbolToSecondMap[char]);
numberBeforeNextChar = 0;
}
return seconds;
}
console.log(getSecondsFromTimeString('1s'))
console.log(getSecondsFromTimeString('10s'))
console.log(getSecondsFromTimeString('1s4m10d3h'))
console.log(getSecondsFromTimeString('1s4m03h1h'))
console.log(getSecondsFromTimeString('10d'))
I tried this, is it helpful to you
let d = '1H1s';
d = d.toLowerCase();
let sec = 0;
if(d.indexOf('h') > -1) {
if (d.indexOf('m') == -1) {
d = d.substring(0, d.indexOf('h') + 1) +"0m"+d.substring(d.indexOf('h') + 1);
}
}
let newDs = d.replace('h',':').replace('m',':').replace('s','').split(':');
newDs.forEach((v, i) => sec += Math.pow(60, (newDs.length - i - 1)) * v);
console.log(sec);
I have functions which change value variable totalTime.
When I use first func value equals 189 - 50 (139).
After using second func I want to receive current value - 8 (131) but I have 189 - 8.
What am I doing wrong?
let totalTime = 189; // *
function calcTime(){
let hours = Math.trunc(totalTime/60);
let minutes = totalTime % 60;
let formatted = hours + 'h ' + minutes + 'm';
fullTimeDefault.innerHTML = formatted;
}
function workTimeDecrease() {
if(valueElem[0]) {
if (+valueElem[0].innerHTML === 15) {
return false
} else{
valueElem[0].innerHTML = parseInt(valueElem[0].innerHTML, 10) - step;
}
for(i = 0; i < barElem.length; i++) {
barElem[i].style.width = parseInt(valueElem[0].innerHTML, 10) + '%';
}
totalTime -= 50 // (1!)
}
}
function shortBreakDecrease() {
if(valueElem[2]) {
if (+valueElem[2].innerHTML === 3) {
return false
} else {
valueElem[2].innerHTML = parseInt(valueElem[2].innerHTML, 10) - step;
}
for(i = 0; i < barElem2.length; i++) {
barElem2[i].style.width = parseInt(valueElem[2].innerHTML, 10) + '%';
}
totalTime -= 8 // (2!)
}
}
elem.onclick = function(event) {
if (event.target.closest('.down-time')) {
workTimeDecrease();
calcTime();
} else if (event.target.closest('.up-time')) {
workTimeIncrease();
calcTime();
}
if (event.target.closest('.down-short-break')) {
shortBreakDecrease();
calcTime();
} else if (event.target.closest('.up-short-break')) {
shortBreakIncrease();
calcTime();
}
}
My thoughts are that this line isn't assigning totalTime to your output, though it is being modified internally (also "step" is defined nowhere)
valueElem[0].innerHTML = parseInt(valueElem[0].innerHTML, 10) - step;
Maybe if you pass in step as 50 then 8 in the 2 calls (change headers to take as parameter):
function workTimeDecrease(int step) {
function shortBreakDecrease(int step) { ...
Change:
valueElem[0].innerHTML = parseInt(valueElem[0].innerHTML, 10) - step;
...
valueElem[2].innerHTML = parseInt(valueElem[0].innerHTML, 10) - step;
To:
valueElem[0].innerHTML = totalTime - step;
...
valueElem[2].innerHTML = totalTime - step;
And change both totalTime assignemts to:
totalTime -= step;
You could also do an alert or log to console right after totalTime assignment to make sure that's not the problem (or all over, helps to check values - I use those extensively for debugging, sometimes every single line).
I need help with this between function. My clock here is 24 hours.
I always get the "else" option. What is wrong with the code?
// Get time
var today = new Date();
var time = today.getHours();
console.log(time); // 8 o clock right now when I am testing
// Between function
Number.prototype.between = function(first, last) {
return first < last ? this >= first && this <= last : this >= last && this <= first;
};
// Do something
if (time.between(7, 9)) {
console.log("between(7, 9)",time.between(7, 9))
}
if (time.between(9, 15)) {
console.log("between(9, 15)",time.between(9, 15))
}
if (time.between(15, 18)) {
console.log("between(15, 18)",time.between(15, 18))
}
// and so on
else {
console.log("else")
}
The else only connects the last if. Just write else ifs
// Get time
var today = new Date();
var time = today.getHours();
console.log(time); // 8 o clock right now when I am testing
// Between function
Number.prototype.between = function(first, last) {
return first < last ? this >= first && this <= last : this >= last && this <= first;
};
// Do something
if (time.between(7, 9)) {
console.log("between(7, 9)",time.between(7, 9))
}
else if (time.between(9, 15)) {
console.log("between(9, 15)",time.between(9, 15))
}
else if (time.between(15, 18)) {
console.log("between(15, 18)",time.between(15, 18))
}
// and so on
else {
console.log("else")
}
I wanted something to be returned as output but not able to.
function arrsort(arr){
return arr.sort(function(a, b){return a - b});
}
const binarySearch=(arr,num,start,end)=>{
arr=arrsort(arr);
start=0;
end=arr.length;
var mid = Math.floor(end / 2);
if (arr[mid] === num) {
return true;
} else if (arr[mid] < num && end > 1) {
binarySearch(arr.splice(mid, Number.MAX_VALUE), num,start,end);
} else if (arr[mid] > num && end > 1) {
binarySearch(arr.splice(start, mid), num,start, end);
} else {
return false;
}
}
I expected the output as true or false.
You need some more return statements before calling the same function again.
And while you return for every true if statement, you could omit else.
function arrsort(arr) {
return arr.sort(function(a, b) {
return a - b;
});
}
const binarySearch = (arr, num, start, end) => {
arr = arrsort(arr);
start = 0;
end = arr.length;
var mid = Math.floor(end / 2);
if (arr[mid] === num) {
return true;
}
if (arr[mid] < num && end > 1) {
return binarySearch(arr.splice(mid, Number.MAX_VALUE), num, start, end);
}
if (arr[mid] > num && end > 1) {
return binarySearch(arr.splice(start, mid), num, start, end);
}
return false;
}
the code should be able to handle any amount up to 20000, For example, suppose the Entered amount is 2600 when the balance in the card is 3000. Will output following :
New Balance - 400
Notes:
2000 * 1
500 * 1
100 * 1
(only three banknotes 2000, 500, 100) and the cash limit is 20000
I am new in the javascript world, and I am not able to write the code, could anyone help me out??? please!
var h = 5;
var f = 2;
var t = 1;
var ifAmtLessThn2000 = ifAmtLessThn2000(n) {
var temp;
if (n < 500) {
h += (n / 100);
return {
h
}
} else if (n >= 500 && n < 2000) {
f += n / 500;
h += (n - 500) / 100;
return {
h,
f
}
} else {
temp = n - 1500;
if (temp < 500) {
h += (temp / 100);
return {
h
}
console.log('hundred : ' + h);
} else {
f += 1;
h += (temp - 500) / 100;
console.log('five hundred : ' + f);
console.log('hundred : ' + h);
return {
f,
h
}
}
}
}
var ifAmtGreaterthan2000 = (n) => {
var h = 0;
var f = 0;
var t = 0;
var tt = 0;
var temp;
if (n < 2000) {
tt += (n / 2000);
}
else if (n >= 2000 && n < 10000) {
f += n / 500;
h += (n - 500) / 100;
}
else {
temp = n - 1500;
if (temp < 500) {
h += (temp / 100);
}
else {
f += 1;
h += (temp - 500) / 100;
}
}
}
var checkAmt = (n) => {
if (n < 100 || (n % 100) > 0) {
console.log("Invalid Amount : less than 100 ");
} else {
if (n > 20000) {
console.log("ATM Cash Limit exceeds.");
} else {
if (n <= 2500) {
ifAmtLessThn2500(n);
console.log(h + " x 100");
console.log(f + " x 500");
} else {
temp = n - 2500;
t += temp / 1000;
if (temp > 500)
temp = temp - (1000 * (t - 1));
ifAmtLessThn2500(temp);
console.log(h + " x 100");
console.log(f + " x 500");
console.log(t + " x 1000");
}
}
}
}
checkAmt(2500);
Sorry for a dumb program, but I need help please can anyone give me a solution in typeScript code, returning the req denomination in array!!
const withdraw = (amount) => {
let hundredNotes = 0;
let fiftyNotes = 0;
let twentyNotes = 0;
while (amount >= 20) {
if (
amount >= 100 &&
((amount % 100) % 50 === 0 || (amount % 100) % 20 === 0)
) {
amount -= 100;
hundredNotes++;
} else if (
amount >= 50 &&
((amount % 50) % 100 === 0 || (amount % 50) % 20 === 0)
) {
amount -= 50;
fiftyNotes++;
} else {
amount -= 20;
twentyNotes++;
}
}
return [hundredNotes, fiftyNotes, twentyNotes];
};
console.log(withdraw(230));
console.log(withdraw(250));
amtArray = [2000, 500, 100]; // the denomination you want to find.
for (let i = 0; i < this.amtArray.length; i++) {
this.resultArray.push(Math.floor(total / this.amtArray[i]));
// Get the new total
total = total % this.amtArray[i];
}
var twothousands_notes = this.resultArray[0];
var fivehundred_notes = this.resultArray[1];
var hundred_notes = this.resultArray[2];
console.log('calculated amt : ' + '100 : ' +
hundred_notes + ' 500 : ' +
fivehundred_notes + ' 2000 : ' +
twothousands_notes);
Based on the amount you can adjust the logic.
Hope this helps.. :)
this would cover all your cases
function dispenseCase (inputAmount) {
var notes = [];
var balance = 3000;
if(inputAmount !== 0 && inputAmount % 100 == 0 && inputAmount <= balance) {
var notes2000 = Math.round(inputAmount / 2000);
var notes500 = Math.round((inputAmount - (notes2000 * 2000)) / 500 );
var notes100 = Math.round((inputAmount - ((notes2000 * 2000) + (notes500 * 500))) / 100);
notes.push(notes2000);
notes.push(notes500);
notes.push(notes100);
console.log("balance in you account = ", balance - inputAmount);
console.log(notes);
}
else if (inputAmount > balance) {
console.log("Insufficient balance in your account");
}
else if ( inputAmount % 100 != 0 || inputAmount < 100 ) {
console.log( "Invalid amount entered, amount should be multiples of 100");
}
}
dispenseCase(2600);
ATM denomination program in Javascript.
Here, It'll find the minimum number of notes of different denominations that sum the entered amount. Starting from the highest denomination note to the lowest notes.
function countCurrency(amount) {
var notes = [2000, 500, 200, 100];
var noteCounter = [0, 0, 0, 0];
for (var i = 0; i < 4; i++) {
if (amount >= notes[i]) {
noteCounter[i] = Math.floor(amount / notes[i]);
amount = amount - noteCounter[i] * notes[i];
}
}
// Print notes denomination
console.log("Denomination Count:");
for (var j = 0; j < 4; j++) {
if (noteCounter[j] !== 0) {
console.log(notes[j] + " : " + noteCounter[j]);
}
}
}
countCurrency(3300);
Here is the working example
https://codesandbox.io/s/atm-denomination-javascript-o0wb4?file=/src/index.js
this would print the number of notes in a 2000, 500, 100 order for the amount you enter
function dispenseCase (inputAmount) {
var notes = [];
if(inputAmount !== 0) {
var notes2000 = Math.round(inputAmount / 2000);
var notes500 = Math.round((inputAmount - (notes2000 * 2000)) / 500 );
var notes100 = Math.round((inputAmount - ((notes2000 * 2000) + (notes500 * 500))) / 100);
notes.push(notes2000);
notes.push(notes500);
notes.push(notes100);
console.log(notes);
}
}
dispenseCase(2600);
hope this helps
//ATM Cash Denominations //Cash Input Value Already been Provided in this method // You may use a input stream method to input a user input value
public class Denominations
{
public static void main(String args[])//throws IOException
{
int notes[]={5000,2000,1000,500,100}; //storing all the denominations in an array
int amount = 27000;
int copy=amount; //Making a copy of the amount
int totalNotes=0,count=0;
System.out.println("\nATM CASH DENOMINATIONS: \n");
for(int i=0;i<5;i++) //Since there are 5 different types of notes, hence we check for each note.
{
count=amount/notes[i]; // counting number of notes[i] notes
if(count!=0) //printing that denomination if the count is not zero
{
System.out.println(notes[i]+"\tx\t"+count+"\t= "+notes[i]*count);
}
totalNotes=totalNotes+count; //finding the total number of notes
amount=amount%notes[i]; //finding the remaining amount whose denomination is to be found
}
System.out.println("--------------------------------");
System.out.println("TOTAL\t\t\t= "+copy); //printing the total amount
System.out.println("--------------------------------");
System.out.println("Total Number of Notes\t= "+totalNotes); //printing the total number of notes
}
}
let sumToDenominate=Math.floor(Math.random() * 100);
let billsValues = [100, 50, 20, 10, 5,1];
let restAfterDenomination = [];
let billsNumber = [];
function denomination(sum, billsValues) {
printInitialValue( sumToDenominate, billsValues);
initializeArray( sumToDenominate, billsValues);
for (let i = 1; i <= billsValues.length; i++) {
if (restAfterDenomination[i - 1] > 0 || restAfterDenomination < billsNumber[i]) {
billsNumber.push(Math.floor(restAfterDenomination[i - 1] / billsValues[i]));
console.log(`bill's number of `, billsValues[i], "=>", billsNumber[i]);
restAfterDenomination.push(restAfterDenomination[i - 1] - (billsNumber[i] * billsValues[i]));
} else {
console.log(`rest is less than smallest bill or equal to 0`);
billsNumber.push(0);
// break;
}
}
}
function printInitialValue(amount, billsValue) {
console.log("Denomination sumToDenominate: ", amount);
console.log("____________");
for (const logEntry of billsValue) {
console.log(logEntry);
}
console.log("__________");
}
function initializeArray(amount, billsValues) {
billsNumber.push(Math.floor(amount / billsValues[0]));
console.log(`bill's number of`, billsValues[0], "=>", billsNumber[0]);
restAfterDenomination.push(amount - (billsNumber[0] * billsValues[0]));
denomination(sumToDenominate,billsValues);