Date Evaluation in JS - javascript

I need to validate a credit card expiry date, I have the javascript code but I don't know how to customize it for my need.
this is my code, I only need the date in a mm/yy format but this code has the date format in mm/dd/yyyy.
var date = document.getElementById('date');
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);
});

Related

JavaScript : return maximum possible `HH:MM`

Leetcode problem:
You are given a string that represents time in the format hh:mm. Some of the digits are blank (represented by ?). Fill in ? such that the time represented by this string is the maximum possible. Maximum time: 23:59, minimum time: 00:00. You can assume that input string is always valid.
You can use the replace function ability of String.replace. The second parameter passed in is the position of the ?, so use that to look up the max value for that position in an array.
const maxValues = ["2", "3", ":", "5", "9"];
const maxTime = (time) => time.replace(/\?/g, (s, p, str) => {
if (p === 1 && str[0] !== '2' && str[0] !== '?' ) {
return '9';
}
return maxValues[p];
});
console.log(maxTime("?1:1?"))
console.log(maxTime("??:??"))
console.log(maxTime("11:11"))
console.log(maxTime("1?:?1"))
This is not a very elegant solution but it addresses the problem I pointed out in my reply to James, where the send H in HH can be either 9 or 3 depending on the time. This also is just different but also valid.
maxTime = (strTime) => {
let [...str] = strTime;
if (str[0] == "?") { str[0] = "2"; }
if (str[1] == "?" && str[0] < "2") { str[1] = "9"; } else { str[1] = "3"; }
if (str[3] == "?") { str[3] = "5"; }
if (str[4] == "?") { str[4] = "9"; }
return str.join('');
}
console.log(maxTime("?2:22")); // 22:22
console.log(maxTime("2?:22")); // 23:22
console.log(maxTime("22:?2")); // 22:52
console.log(maxTime("22:2?")); // 22:29
console.log(maxTime("0?:??")); // 09:59
console.log(maxTime("1?:??")); // 19:59
console.log(maxTime("??:??")); // 23:59
or a loop
const max = "29:59";
maxTime = (strTime) => {
let [...str] = strTime;
for (x = 0; x < 5; x++) { if (strTime[x] == "?") { str[x] = max[x]; }}
if (str[0] == "2" && strTime[1] == "?") { str[1] = "3"; }
return str.join('');
}
console.log(maxTime("?2:22")); // 22:22
console.log(maxTime("2?:22")); // 23:22
console.log(maxTime("22:?2")); // 22:52
console.log(maxTime("22:2?")); // 22:29
console.log(maxTime("0?:??")); // 09:59
console.log(maxTime("1?:??")); // 19:59
console.log(maxTime("??:??")); // 23:59
maxTime = (time) => {
const timeArr = time.split(":");
let hr = timeArr[0];
let mn = String(timeArr[1]);
if (mn.includes("?")) {
const mnArr = mn.split("");
if (mnArr[0] === "?" && mnArr[1] === "?") {
mn = "59";
} else if (mnArr[0] === "?") {
mn = "5" + mnArr[1];
} else if (mnArr[1] === "?") {
const temp = mnArr[0] === "5" ? "9" : "0";
mn = mnArr[0] + temp;
}
}
if (hr.includes("?")) {
const hrArr = hr.split("");
if (hrArr[0] === "?" && hrArr[1] === "?") {
hr = "23";
} else if (hrArr[0] === "?") {
hr = "2" + hrArr[1];
hr = Number(hr) <= 24 ? "1" + hrArr[1] : hr;
} else if (hrArr[1] === "?") {
const temp = hrArr[0] === "2" ? "3" : "9";
hr = hrArr[0] + temp;
}
}
return `(${time}) => ${hr}:${mn}`;
}

Optimize my JavaScript Code using Date and Time

I would like learn how this code can be done in a more proficient manner.
I am new to JavaScript and I know how to do things but in a simple way I guess.
Any help would be appreciated.
var urlstart = "domain.com";
var urlend = "?blah";
var serverTime = "Thu Mar 07 11:23:06 PST 2019";
var st = serverTime.toLowerCase();
var m = st.slice(4,7);
if ( m === "jan") {
var m = "01"
}
if (m === "feb") {
var m = "02"
}
if (m === "mar") {
var m = "03"
}
if (m === "apr") {
var m = "04"
}
if (m === "may") {
var m = "05"
}
if (m === "jun") {
var m = "06"
}
if (m === "jul") {
var m = "07"
}
if (m === "aug") {
var m = "08"
}
if (m === "sep") {
var m = "09"
}
if (m === "oct") {
var m = "10"
}
if (m === "nov") {
var m = "11"
}
if (m === "dec") {
var m = "12"
}
var d = st.slice(8,10);
var y = st.slice(-2);
var t = st.slice(11,23);
var th = t.slice(0,2);
var th = Math.floor(th);
/* 9pm or After */
if (th > 20 ) {
/* End Of Month - add 1 to Month value and change Day value 1 */
if ( ( d == "30" && ( m == "04" || m == "06" || m == "09" || m == "11")) ||
( d == "31" && ( m == "01" || m == "03" || m == "05" || m == "07" || m == "08" || m == "10"))
|| ( d == "28" && m == "02") ) {
var m = Math.floor(m);
var m = m + 1;
var m = m.toString();
var m = m.replace(/\d+/g, function(m){ return "0".substr(m.length - 1) + m; });
var d = "01";
window.location.href = urlstart+m+d+y+urlend;
}
/* End Of the Year - Change M and Day and Year */
else if ( m =="12" && d=="31" ) {
var m = "01";
var d = "01";
var y = Math.floor(y);
var y = y + 1;
var y = y.toString();
var y = y.replace(/\d+/g, function(y){ return "0".substr(y.length - 1) + y; });
window.location.href = urlstart+m+d+y+urlend;
}
else { /* Days that are not End Of Month */
var d = Math.floor(d);
var d = d + 1;
var d = d.toString();
var d = d.replace(/\d+/g, function(d){ return "0".substr(d.length - 1) + d; });
window.location.href = urlstart+m+d+y+urlend;
}
} else {
window.location.href = urlstart+m+d+y+urlend;
}
Thank you for your time.
................................................................................................................................................

How to get String output as in single quote in javascript

Advance thanks, Question looks like simple but i could not able to find the solution.
function sumStrings(a, b)
{
return +a + +b;
}
sumStrings('1','2') //=>3
Expected output
sumStrings('1','2') // => '3'
After addition, add ' to beginning and end.
function sumStrings(a, b){
return "'" + (Number(a) + Number(b)) + "'";
}
console.log(sumStrings('1','2'));
function sumStrings(a, b) {
// Separate decimal part here
var pointa = a.indexOf(".");
var pointb = b.indexOf(".");
var deca = pointa != -1 ? a.substring(pointa + 1) : "0";
var decb = pointb != -1 ? b.substring(pointb + 1) : "0";
if (deca.length < decb.length)
deca += (Math.pow(10, decb.length - deca.length)).toString().substring(1);
else
decb += (Math.pow(10, deca.length - decb.length)).toString().substring(1);
var inta = pointa != -1 ? a.substring(0, pointa) : a;
var intb = pointb != -1 ? b.substring(0, pointb) : b;
// console.log(deca + " " + decb);
var decc = addBigInt(deca, decb);
var intc = addBigInt(inta, intb);
if (decc.length > deca.length) {
intc = addBigInt(intc, "1");
decc = decc.substring(1);
}
var lastZero = decc.length - 1;
while (lastZero >= 0 && decc[lastZero] == "0") {
lastZero--;
}
if (lastZero >= 0)
return intc + "." + decc.substring(0, lastZero + 1);
else
return intc;
}
function addBigInt(a, b) {
var inda = a.length - 1;
var indb = b.length - 1;
var c = [];
const zero = "0".charCodeAt(0);
var carry = 0;
var sum = 0;
while (inda >= 0 && indb >= 0) {
var d1 = a.charCodeAt(inda--) - zero;
var d2 = b.charCodeAt(indb--) - zero;
sum = (d1 + d2 + carry);
carry = Math.floor(sum / 10);
sum %= 10;
c.unshift(sum);
}
if (inda >= 0) {
while (carry && inda >= 0) {
sum = a.charCodeAt(inda--) - zero + carry;
c.unshift(sum % 10);
carry = Math.floor(sum / 10);
}
c.unshift(a.substring(0, inda + !carry));
} else {
while (carry && indb >= 0) {
sum = b.charCodeAt(indb--) - zero + carry;
c.unshift(sum % 10);
carry = Math.floor(sum / 10);
}
c.unshift(b.substring(0, indb + !carry));
}
if (carry)
c.unshift(carry);
return c.join("");
}
console.log(sumStrings("1","2"));
console.log(sumStrings("800","9567"));
console.log(sumStrings("99.1","1"));
console.log(sumStrings("00103","08567"));
console.log(sumStrings("50095301248058391139327916261.5","81055900096023504197206408605"));
If you want to escape the single quote, you can try to add a backslash before the single quote.
i.e.
var x = '\'5\'';
With the new template literal you can try this:
a=`'5'`;
console.log(a);

howto convert a number to a clever number with specific length and k, m, b

for example I have this number:
1,234,567.89
And I want to convert this number to a number with a specific length like these:
1M
01M
1.2M
1.23M
1.234M
1.2346M
1.23457M
1,234,568
01,234,568
1,234,567.9
1,234,567.89
Is there any javascript function, plugin or something for doing this in such a way (with K, M, B...)?
I don't understand your downvotes because this a not a duplicated question und I found NOTHING similar. So i made it by myself and it works ;)
function number(num, size) {
var s = num;
var l1 = s.toString().length;
if (l1 > size && num > 1) s = Math.floor(num);
var l2 = s.toString().length;
if (l2 > size) {
if (num >= 1e3 && num < 1e6) {
s = num / 1e3;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'k';
} else if (num >= 1e6 && num < 1e9) {
s = num / 1e6;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'M';
} else if (num >= 1e9 && num < 1e12) {
s = num / 1e9;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'G';
} else if (num >= 1e12 && num < 1e15) {
s = num / 1e12;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'T';
} else if (num >= 1e15 && num < 1e18) {
s = num / 1e18;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'P';
} else if (num >= 1e18 && num < 1e21) {
s = num / 1e18;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'E';
} else if (num >= 1e21 && num < 1e24) {
s = num / 1e21;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'Z';
} else if (num >= 1e24 && num < 1e27) {
s = num / 1e24;
var m = Math.max(0, size - 2 - (s.toString().split('.')[0] || num).length);
s = ((m == 0) ? Math.floor(s) : s.toFixed(m)) + 'Y';
}
}
var l3 = s.toString().length;
if (l3 > size) s = '-';
var s = s.toString();
while (s.length < size) s = s.charAt(0) == '-' ? '-' + s : '0' + s;
var startZeros = /^(0)\1+/.exec(s),
startZerosCount = (startZeros != null) ? startZeros[0].length : 0,
decimalCount = (num.toString().split('.')[1] || []).length;
if (startZerosCount >= 2 && decimalCount > 0 && s.indexOf('.') < 0) {
var decimals = num.toString().split('.')[1],
movedDigits = Math.min(startZerosCount, decimalCount),
lastChar = s.substring(s.length - 1);
if (isNaN(lastChar)) {
s = s.substring(0, s.length - 1);
s = s.substring(movedDigits) + '.' + decimals.substring(0, movedDigits - 1);
s += lastChar;
} else {
s = s.substring(movedDigits) + '.' + decimals.substring(0, movedDigits - 1);
}
}
return s;
}
The output for 784432432.9999 is:
-
--
---
784M
0784M
784.4M
784.43M
784.432M
784432432
0784432432

javascript updatesum() problems

I have the following JavaScript code which is writing in a HTML form:
<script type="text/javascript">
function updatesum() {
document.functie.column8.value = (document.functie.column6.value -0) * (document.functie.column7.value -0);
document.functie.column12.value = (document.functie.column10.value -0) * (document.functie.column11.value -0);
document.functie.column16.value = (document.functie.column14.value -0) * (document.functie.column15.value -0);
document.functie.column20.value = (document.functie.column18.value -0) * (document.functie.column19.value -0);
}
and with the php form like:
echo "<td><input name=\"column6\" onChange=\"updatesum()\"></td>";
echo "<td><input name=\"column7\" onChange=\"updatesum()\"></td>";
The problem is that when I put some values in the first form, it gives me the sum, but if I don't put some values it gives me zero, which I do not want:
http://img17.imageshack.us/img17/5456/hyhu.png http://img17.imageshack.us/img17/5456/hyhu.png
In the bottom I have a sum of all the values from the 3rd column, but the it gives me numbers like 2400 or 2300.44, and I want an output of 2,400 or to roundup the 2300.44 to 2,300. How can I do that?
1/ You're multiplying with a value '' automatically cast to an integer, so 0. This is normal that you end up with 0. If you do not want that, you'll have to create a function that check the value of the inputs and return '' if one of them is ''
something like:
function multiply(v1, v2) {
if (v1 === '' || v2 === '' || isNaN(v1) || isNaN(v2)) {
return '';
}
return v1*v2;
}
2/ You'll need to add a format function, that will format your code and add the , where it must and get ride of the decimals (or use links in that comment javascript updatesum() problems) :
function formatNumber(num) {
var formatted = '';
num = Math.ceil(num) + '';
for (var i = num.length - 1, j = 0; c = num.charAt(i); i--) {
if (j % 3 === 0) {
c = c + ',';
}
formatted = c + formatted;
j++;
}
return formatted.trim();
}
You asked for an example. This should do it in place of your current updatesum function:
function multiply(v1, v2) {
if (v1 === '' || v2 === '' || isNaN(v1) || isNaN(v2)) {
return '';
}
return v1*v2;
}
function multiplyAndFormat(v1, v2) {
return formatNumber(multiply(v1, v2));
}
function formatNumber(num) {
var formatted = '';
num = Math.ceil(num) + '';
for (var i = num.length - 1, j = 0; c = num.charAt(i); i--) {
if (j % 3 === 0) {
c = c + ',';
}
formatted = c + formatted;
j++;
}
return formatted.trim();
}
function updatesum() {
document.functie.column8.value = multiplyAndFormat(document.functie.column6.value, document.functie.column7.value);
document.functie.column12.value = multiplyAndFormat(document.functie.column10.value, document.functie.column11.value);
document.functie.column16.value = multiplyAndFormat(document.functie.column14.value, document.functie.column15.value);
document.functie.column20.value = multiplyAndFormat(document.functie.column18.value, document.functie.column19.value);
}
should do it

Categories

Resources