Get amount of seconds from a formatted time string - javascript

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

Related

Sorting an integer without using string methods and without using arrays

can anyone come with an idea of how to sort an integer without using an array, and without using string methods as well as sort() method?
for example
input: 642531
output: 123456
I started by writing 2 simple functions - one which checks the length of the number, the other one splits the integer at some point and switches between 2 desired numbers. Below are the 2 functions.
I got stuck with the rest of the solution...
function switchDigits(num, i) { // for input: num=642531, i = 4 returns 624135
let temp = num;
let rest = 0;
for (let j = 0; j < i - 1; j++) {
rest = rest * 10;
rest = rest + temp % 10;
temp = (temp - temp % 10) / 10;
}
let a = temp % 10;
temp = (temp - a) / 10;
let b = temp % 10;
temp = (temp - b) / 10;
temp = Math.pow(10, i - 2) * temp;
temp = temp + 10 * a + b;
temp = Math.pow(10, i - 1) * temp;
temp = temp + rest;
return temp;
}
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
let num = 642534;
let i = checkHowManyDigits(num);
console.log(switchDigits(num));
It actually complicated requirement and so does this answer. It's pure logic and as it is it's a question from a test you should try understanding the logic on your own as a homework.
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
function sortDigit(numOriginal) {
let i = checkHowManyDigits(numOriginal);
let minCount = 0;
let min = 10;
let num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d < min) {
min = d;
minCount = 0;
} else if (d === min) {
minCount++;
}
}
let result = 0;
while (minCount >= 0) {
result += min * Math.pow(10, i - minCount - 1);
minCount--;
}
let newNum = 0;
num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d !== min) {
newNum = newNum * 10 + d;
}
}
if (newNum == 0) return result;
else return result += sortDigit(newNum);
}
console.log(sortDigit(642531));
You could have a look to greater and smaller pairs, like
64
46
The delta is 18, which gets an idea if you compare other pairs, like
71
17
where the delta is 54. Basically any difference of two digits is a multiple of 9.
This in mind, you get a function for taking a single digit out of a number and a single loop who is sorting the digits by using the calculated delta and subtract the value, adjusted by the place.
function sort(number) {
const
getDigit = e => Math.floor(number / 10 ** e) % 10,
l = Math.ceil(Math.log10(number)) - 1;
let e = l;
while (e--) {
const
left = getDigit(e + 1),
right = getDigit(e);
if (left <= right) continue;
number += (right - left) * 9 * 10 ** e;
e = l;
}
return number;
}
console.log(sort(17)); // 17
console.log(sort(71)); // 17
console.log(sort(642531)); // 123456
console.log(sort(987123654)); // 123456789
So eventually I found the best solution.
*This solution is based on a Java solution I found in StackOverFlow forums.
let store = 0;
function getReducedNumbr(number, digit) {
console.log("Remove " + digit + " from " + number);
let newNumber = 0;
let repeateFlag = false;
while (number>0) {
let t = number % 10;
if (t !== digit) {
newNumber = (newNumber * 10) + t;
} else if (t == digit) {
if (repeateFlag) {
console.log(("Repeated min digit " + t + " found. Store is : " + store));
store = (store * 10) + t;
console.log("Repeated min digit " + t + " added to store. Updated store is : " + store);
} else {
repeateFlag = true;
}
}
number = Math.floor(number / 10);
}
console.log("Reduced number is : " + newNumber);
return newNumber;}
function sortNum(num) {
let number = num;
let original = number;
let digit;
while (number > 0) {
digit = number % 10;
console.log("Last digit is : " + digit + " of number : " + number);
temp = Math.floor(number/10);
while (temp > 0) {
console.log("subchunk is " + temp);
t = temp % 10;
if (t < digit) {
digit = t;
}
temp = Math.floor(temp/10);
}
console.log("Smallest digit in " + number + " is " + digit);
store = (store * 10) + digit;
console.log("store is : " + store);
number = getReducedNumbr(number, digit);
}
console.log(("Ascending order of " + original + " is " + store));
return store;
}
console.log(sortNum(4214173));
you can see how it works here https://jsfiddle.net/9dpm14fL/1/

24-hours time automatic regex

This is my code:
let input = document.getElementById('f2f11c3');
input.addEventListener('input', addcommas, false);
function addcommas() {
var v = document.getElementById('f2f11c3');
var t = v.value.replace(/\D/g, '');
var i, temp = '';
for (i = t.length; i >= 0; i -= 2) {
if (i == t.length) {
temp = t.substring(i - 2, i);
} else {
if (t.substring(i - 2, i) != "")
temp = t.substring(i - 2, i) + ':' + temp;
}
if (i < 0) {
temp = t.substring(0, i + 2) + ':' + temp;
break;
}
}
v.value = temp;
}
<input type="text" value="" maxlength="8" id="f2f11c3" />
But entered numbers can be greater than 24. Can you fully adapt to the time format?
Example: 23:59:59 and one more 00:00:00
Short answer
Take the string
Split that
Use modulo operator to get the result
Example
var time="24:70:65"; // Suppose we have this time
var parts=time.split(":");// Split the time with :
var part1=(+parts[0] % 24)
var part2=(+parts[1] % 60)
var part3=(+parts[2] % 60)
// Now to get answer in two digits you can
part1 = ("0" + part1).slice(-2);
part2 = ("0" + part2).slice(-2);
part3 = ("0" + part3).slice(-2);
console.log(`${part1}:${part2}:${part3}`)
Hope this will work

Modify this code to remove the "year" part

I have this code and I have to remove the year part of it, it's a formatter for date values in a form, it has to be "DD/MM" but it is "MM/DD/YYYY" can someone help me?
<input type="text" name="datada" id="dtDataDa" placeholder="" value="%dtDataDa%"/>
THIS IS THE CODE I HAVE TO MODIFY
var date = document.getElementById('dtDataDa');
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0)) && num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
date.addEventListener('input', function (e) {
this.type = 'text';
var input = this.value;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
var values = input.split('/').map(function (v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 12);
if (values[1]) values[1] = checkValue(values[1], 31);
var output = values.map(function (v, i) {
return v.length == 2 && i < 2 ? v + ' / ' : v;
});
this.value = output.join('').substr(0, 14);
});
date.addEventListener('blur', function (e) {
this.type = 'text';
var input = this.value;
var values = input.split('/').map(function (v, i) {
return v.replace(/\D/g, '')
});
var output = '';
if (values.length == 3) {
var year = values[2].length !== 4 ? parseInt(values[2]) + 2000 : parseInt(values[2]);
var month = parseInt(values[0]) - 1;
var day = parseInt(values[1]);
var d = new Date(year, month, day);
if (!isNaN(d)) {
document.getElementById('result').innerText = d.toString();
var dates = [d.getMonth() + 1, d.getDate(), d.getFullYear()];
output = dates.map(function (v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join(' / ');
};
};
this.value = output;
});
It makes the form insert only real digits, for the month (1s part) numbers until 12, for the days (2nd part) numbers until 31 and for the year (3rd part) there is no rule.. I would like to have only the month and days part of it so that an example would look like "06/18"
Here you can see it https://codepen.io/user23xx/pen/VdarOL?editors=1010
Thank you for your time.
It's actually quite simple to modify from the code you've shared.
Look for the comments at addEventListener
date.addEventListener('input', function (e) {
this.type = 'text';
var input = this.value;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
var values = input.split('/').map(function (v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 31); //Put 31 instead of 12
if (values[1]) values[1] = checkValue(values[1], 12); //Put 12 instead of 31
var output = values.map(function (v, i) {
return v.length == 2 && i < 2 ? v + ' / ' : v;
});
this.value = output.join('').substr(0, 7); //Update to 7 instead of 14 because full length you want is 7
});
Next we want to update the blur method as below
if (!isNaN(d)) {
document.getElementById('result').innerText = d.toString();
var dates = [d.getDate(),d.getMonth() + 1];//Remove the year part
output = dates.map(function (v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join(' / ');
};
UPDATES:
date.addEventListener('blur', function (e) {
this.type = 'text';
var input = this.value;
var values = input.split('/').map(function (v, i) {
return v.replace(/\D/g, '')
});
var output = '';
if (values.length == 2) {
var dates = [values[0], values[1]];
output = dates.map(function (v) {
v = v.toString();
return v.length == 1 ? '0' + v : v;
}).join(' / ');
};
this.value = output;
});

Money denomination program for ATM in js that would be flexible to handle and dispense money in minimum notes

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

Javascript: How to increment only by 1 (instead of 1+1+1+1+...) while condition is true in a draw loop?

I'm attempting to build an app in Processing.js that rotates an array of objects every 15 min (seconds for now). My idea was to just increment the index every time the second hand strikes 0/15/30/45, but since it's inside a draw loop it executes +1 times every frame in that second, setting my index to like, 30. How can I ensure only one increment gets through?
var i = 0;
var draw = function() {
background(148, 221, 255);
var s = second();
var m = minute();
var h = hour();
text(h + " : " + m + " : " + s, 5, 395);
var Rotation = function() {
if (s === 0 || s === 15 || s === 30 || s === 45) {
i+= 1;
Array[i];
}
};
Rotation();
text(i,50,50);
};
Thanks
Add a variable that checks if the current inverval (0,15,30,45) has already been used / set.
var i = 0;
var last_interval;
var draw = function() {
background(148, 221, 255);
var s = second();
var m = minute();
var h = hour();
text(h + " : " + m + " : " + s, 5, 395);
var Rotation = function() {
if (s === 0 || s === 15 || s === 30 || s === 45) {
if(last_interval === undefined || last_interval != s){
last_interval = s;
i+= 1;
Array[i];
}
}
};
Rotation();
text(i,50,50);
};

Categories