Freshbooks like invoice number increment in javascript - javascript

I need to create invoice number incrementing function like freshbooks. How t works in freshbooks is it increments number and alphabet both.
Condition 1:
if my invoice number is 0000012 it should be incremented to 0000013
Condition 2:
if my invoice number is 000001a it should be incremented to 000001b
and so on.
Any idea on how to do that?
My attempt:
function replaceCharAt(string, index, character){
return string.substr(0, index) + character + string.substr(index + character.length)
}
function generateInvoiceNumber(invoiceNumber, useIndex){
var useIndex = useIndex || invoiceNumber.length - 1;
var invoiceNumber = invoiceNumber.trim();
var incrementChar = invoiceNumber[useIndex];
if(incrementChar == '9' || incrementChar == 'z' || incrementChar == 'Z'){
if(incrementChar == 9){
invoiceNumber = replaceCharAt(invoiceNumber, useIndex, '0');
}
else{
invoiceNumber = replaceCharAt(invoiceNumber, useIndex, 'a');
}
return generateInvoiceNumber(invoiceNumber, useIndex - 1);
}
else{
var replaceChar = String.fromCharCode(incrementChar.charCodeAt(0) + 1);
invoiceNumber = replaceCharAt(invoiceNumber, useIndex, replaceChar);
}
return invoiceNumber;
}
This does produce the correct results. but i am not sure about all conditions and if it will hang the event loop. I will write some test and try

I think I this works well now. I have tested it against most of the scenarios.
module.exports = {
replaceCharAt: function replaceCharAt(string, index, character){
var string = string.split('');
string[index] = character;
return string.join('');
},
generateInvoiceNumber: function generateInvoiceNumber(invoiceNumber, useIndex){
var invoiceNumber = invoiceNumber.trim();
if(typeof useIndex === 'undefined' || useIndex === -1 ){
useIndex = invoiceNumber.length - 1;
}
var incrementChar = invoiceNumber[useIndex];
if(incrementChar == '9' || incrementChar == 'z' || incrementChar == 'Z'){
if(incrementChar == 9){
invoiceNumber = this.replaceCharAt(invoiceNumber, useIndex, '0');
}
else{
invoiceNumber = this.replaceCharAt(invoiceNumber, useIndex, 'a');
}
if(useIndex === 0){
return invoiceNumber = '1'+invoiceNumber;
}
return this.generateInvoiceNumber(invoiceNumber, useIndex - 1);
}
else{
var replaceChar = String.fromCharCode(incrementChar.charCodeAt(0) + 1);
invoiceNumber = this.replaceCharAt(invoiceNumber, useIndex, replaceChar);
}
return invoiceNumber;
}
};

Related

convert a string containing boolean values to a boolean

If I have this ;
var a = "(true && false) && true && false"
And if I want to evaluate this string , what are the options ?
If I say, this code will be generated in the browser but there will be absolutely no user input in it , would it be safe to use eval ?
If not, what is the most performant way of parsing it ?
EDIt :
By the way, the string is dynamic , so I can't gaurantee that it's always like above , so it could be :
var a = "(true && false) || (true && (true && false)) && true && false"
FIY :
I know I can use eval, all I'm asking is, why I shouldn't use eval, or is there any other options?
EDIT : the original problem :
var a = function(){ return false} // all of them always return a boolean
var b = function(){ return true}
var c = function(){ return true}
var d = function(){ return false}
var conditions = "(a && b) && c && d"
I can't change the above code , I need to parse it, I need the condition to be evaluated ;
function ExecuteJavascriptString() {
var n = 0;
var s = "(true || false) || (true || (true || false)) && true";
var ifstate = " if (" + s + ") { console.log('done'); } ";
setTimeout(ifstate, 1);
}
ExecuteJavascriptString()
I was thinking maybe you can atleast verify that the string contains what you think it should contain, before running eval on it, using the RegExp /(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g:
var validExp = "(true && false && true) || (true && (true && false)) && true";
var evilExp = "(true && false && true) || (true && (true && false)) && true function() { console.log('do evil stuff'); }";
console.log(evalBoolStr(validExp)); //false
console.log(evalBoolStr(evilExp)); //Invalid input
function evalBoolStr(str) {
if(str.match(/(?:(?:true)|(?:false)|(?:&&)|(?:\|\|)|[()\s])/g).join('') === str) {
return eval(str);
}
return 'Invalid input';
}
An attempt at actually writing a parser for boolean strings:
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "(true && false) && true && false";
var exp3 = "(true && !false) && true && !false";
var exp4 = "(a && b) && c && d";
console.log(exp1 + ' = ' + parseBoolStr(exp1));
console.log(exp2 + ' = ' + parseBoolStr(exp2));
console.log(exp3 + ' = ' + parseBoolStr(exp3));
console.log(exp4 + ' = ' + parseBoolStr(exp4));
function parseBoolStr(str) {
var expressions = {};
var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
var expressionIndex = 0;
str = str.trim();
while (str.match(expressionRegex)) {
var match = str.match(expressionRegex)[0];
var expression = 'boolExpr' + expressionIndex;
str = str.replace(match, expression);
match = match.replace('(', '').replace(')', '');
expressions[expression] = match;
expressionIndex++;
}
return evalBoolStr(str, expressions);
}
function evalBoolStr(str, expressions) {
var conditions = str.split(' ');
if (conditions.length > 0) {
var validity = toBoolean(conditions[0], expressions);
for (var i = 1; i + 1 < conditions.length; i += 2) {
var comparer = conditions[i];
var value = toBoolean(conditions[i + 1], expressions);
switch (comparer) {
case '&&':
validity = validity && value;
break;
case '||':
validity = validity || value;
break;
}
}
return validity;
}
return 'Invalid input';
}
function toBoolean(str, expressions) {
var inversed = 0;
while (str.indexOf('!') === 0) {
str = str.replace('!', '');
inversed++;
}
var validity;
if (str.indexOf('boolExpr') === 0) {
validity = evalBoolStr(expressions[str], expressions);
} else if (str == 'true' || str == 'false') {
validity = str == 'true';
} else {
validity = window[str]();
}
for (var i = 0; i < inversed; i++) {
validity = !validity;
}
return validity;
}
function a() {
return false;
}
function b() {
return true;
}
function c() {
return true;
}
function d() {
return false;
}
Usage would then simply be parseBoolStr('true && false'); //false

code does not validate email from a form, in javascpricpt

hi i font know if this is the right place to ask this question but i have a problem with my code that i cannot figure out. i have tried many different algorithms and none work. i am trying to validate email from a form.
here is the code (form is in html)
function isValidString(str) {
var quot = "\"";
if (str.indexOf(quot) != -1)
return false;
var badStr = "$%^&*()_+[]{}<>?אבגדהוזחטיכךלמםנןסעפצקרשת";
var i = 0,
p;
while (i < str.length) {
p = badStr.indexOf(str.charAt(i));
if (p != -1)
return false;
i++;
}
return true;
}
function isValidEmail()
{
var str = document.getElementById("email").value;
document.write("email from isValidEmail(str) = " + email);
if (isEmpty(str) || str.length < 5) {
alert("isEmpty(str) || str.length < 5 = false");
return false;
}
if (!isValidString(str)) {
alert("!isValidString(str) = false");
return false;
}
var atSign = str.indexOf('#');
if (atSign == -1 || str.lastIndexOf('#') || atSign === 0 || atSign == str.length - 1) {
alert("atSign == -1 || str.lastIndexOf('#') || atSign == 0 || atSign == str.length - 1 = false");
return false;
}
var dotSign = str.indexOf('.', atSign);
if (dotSign == -1 || dotSign === 0 || dotSign == str.length - 1 || dotSign - atSign < 2) {
alert("dotSign == -1 || dotSign == 0 || dotSign == str.length - 1 || dotSign - atSign < 2 = false");
return false;
}
return true;
no matter what i input it always comes back valid.
here is the part where i apply it:
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
thanks in advance
An example of using the parser library mentioned in my comment.
var eAddr = document.getElementById('eAddr'),
check = document.getElementById('check'),
pre = document.getElementById('out');
check.addEventListener('click', function (evt) {
pre.textContent = !!emailAddresses.parseOneAddress(eAddr.value.trim());
}, false);
<script src="https://rawgit.com/FogCreek/email-addresses/master/lib/email-addresses.js"></script>
<input id="eAddr"></input>
<button id="check">Test pattern</button>
<pre id="out"></pre>
Note: this will accept Goodhertz Inc <support#goodhertz.com> as it stands and you would need to further check the object returned by parseOneAddress to filter these out.
You don't call the rigth function i. e. call
var email = document.getElementById("email").value;
if (isValidString(email)) {
alert("invalid email");
return false;
}
return true;
instead of
var email = document.getElementById("email").value;
if (emailcheck(email)) {
alert("invalid email");
return false;
}
return true;
Using Regular expression is the best method for validating input elements. Below function can validate email perfectly.
function regExValidate_Email(id) {
var email = document.getElementById(id).value;
if (email != '') {
var regExforEmail = /^[a-zA-Z0-9._+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if (regExforEmail.test(email)) {
$("#" + id).css("background-color", "#ffffff");
return true;
}
else {
alert('Please enter a valid email id. \nex: yourname#example.com');
document.getElementById(id).style.backgroundColor = '#feffea';
document.getElementById(id).value = '';
Ctrlid = id;
setTimeout("document.getElementById(Ctrlid).focus()", 1);
return false;
}
}
else { document.getElementById(id).style.backgroundColor = 'white'; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Email: <input type="email" onblur="return regExValidate_Email(this.id)" id="txtEmail" />

NaN error equation

In this javascript code I try to solve a quadratic equation, I've been working on it for an hour and this should tell me the value of a, b and c where y is a(x^2). I'm a relative javascript beginner and would love some help. Why are the values of a, b and c not numbers? The variable names are in italian, in english and in something else(Not even I know what), but I commented what they are. That's one of my bad traits as a student that usually works alone, sorry if it's not easy to understand.
<script type="text/javascript">
var equa=prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var a = 0.0; b = 0.0; c = 0.0;//ax2+bx+c
var prima = true; //before or after equal?
var ope = 1;//1add 2sub 3mul 4div
var lasto = 0.0;//last number, used for div and mul
var lastos = 3; //1a2b3c
var errore=0;//is something messed up?
for(var i = 0; i < equa.length;i=i){
if(equa.charAt(i)=='='){
prima = false;
i++;
}else if(equa.charAt(i)=='+'){
ope=1;
i++;
}else if(equa.charAt(i)=='-'){
ope=2;
i++;
}else if(equa.charAt(i)=='*'){
ope=3;
i++;
}else if(equa.charAt(i)=='/'){
ope=4;
i++;
}else{
var nume = "";//Current number in string form
while(i<equa.length && equa.charAt(i)>'0' && equa.charAt(i)<'9'){
nume+=equa.charAt(i);
i++;
}
var lasnum = 0.0;//current number in float form
var lasval = 3; //1a2b3c
if(equa.charAt(i) == 'x'){
lasnum=parseFloat(nume);
lasval = 2;
}else if(equa.charAt(i) == 'y'){
lasnum=parseFloat(nume);
lasval = 1;
}else{
lasnum = parseFloat(nume);
lasval=3;
}
i++;
if( (ope == 1 || ope == 2) && !(equa.charAt(i) =='*' || equa.charAt(i) == '/')){
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
}else if( (ope==1 || ope == 2) && (equa.charAt(i) =='*' || equa.charAt(i) == '/')){
//zitto e fermo
lasto=lasnum;
lastos=lasval;
}else if( (ope==3||ope == 4)){
if(ope==3){
if(lastos==3){
lasnum*=lasto;
}
if(lastos == 2){
if(lastval==3){
lasnum*=lasto;
lastval=2;
}
if(lastval==2){
lasnum*=lasto;
lastval=1;
}
if(lastval==1){
errore=1;
}
}
if(lastos == 1){
if(lastval == 3){
lasnum*=lasto;
lastval=1;
}else{
errore=1;
}
}
}
if(ope == 4){
if(lastos == 1){
if(lastval==3){
lasnum/=lasto;
lastval=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=2;
}
if(lastval==1){
lasnum/=lasto;
lastval=3;
}
}
if(lastos == 2){
if(lastval==1){
errore=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=3;
}
if(lastval==3){
lasnum/=lasto;
lastval=2;
}
}
if(lastos == 3){
if(lastval==3){
lasnum/=lasto;
}else{
errore=1;
}
}
}
if(equa.charAt(i) =='*' || equa.charAt(i) == '/'){
lasto=lasnum;
lasto=lasval;
}else{
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
lasto=0;
lastos=3;
}
}
}
}
if(errore==0){
alert("a ="+a+" b="+b+" c="+c);
}else{
alert("AOOOOOOo");
}
</script>
Since the expected input should be in the format "15y+3x+5=20" for example, then this is a simple regular expression:
var equa = prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var regex = /^([0-9.]+)y\+([0-9.]+)x\+([0-9.]+)=([0-9.]+)$/;
var matches = regex.exec(equa);
if (matches) {
var a = parseFloat(matches[1]);
var b = parseFloat(matches[2]);
var c = parseFloat(matches[3]) - parseFloat(matches[4]);
var discriminant = b*b - 4*a*c;
if (discriminant < 0) {
alert('No real solutions');
}
else {
var root = Math.sqrt(discriminant);
alert('Root: ' + ((-b + root)/(2*a)) + ', ' + ((-b - root)/(2*a)));
}
}
else {
alert("AOOOOOOo");
}

Javascript - multiple tasks in one function not working

I got a script to trim http or https from a form inputs.
This is my script :
function MakeLinkSafe(){
var f = document.getElementById('f')
str = trim(f.value);
if(str.substr(0, 7) == 'http://'){
f.value = str.substr(7);
}
else if(str.substr(0, 8) == 'https://'){
f.value = str.substr(8);
}
return true;
var fb = document.getElementById('fb')
str = trim(fb.value);
if(str.substr(0, 7) == 'http://'){
fb.value = str.substr(7);
}
else if(str.substr(0, 8) == 'https://'){
fb.value = str.substr(8);
}
return true;
}
When I put a url in my "f" input while I leave my "fb" empty and vice versa, it's working. But when I put url in both of the input. It doesn't work.
Is there any problem ith my codes ? Thank you
It's because you have a return statement after the check on the "f" element...
Change your code as follows:
function MakeLinkSafe() {
var checkF = function () {
var f = document.getElementById('f');
str = trim(f.value);
if (str.substr(0, 7) == 'http://') {
f.value = str.substr(7);
}
else if (str.substr(0, 8) == 'https://') {
f.value = str.substr(8);
}
return true;
}
var checkFB = function () {
var fb = document.getElementById('fb');
str = trim(fb.value);
if (str.substr(0, 7) == 'http://') {
fb.value = str.substr(7);
}
else if (str.substr(0, 8) == 'https://') {
fb.value = str.substr(8);
}
return true;
}
return checkF() && checkFB();
}
You can, of course, create a function accepting an id to take advantage of proper functions, as mentioned by mrida above... Something along the lines of the following might do:
function MakeLinkSafe() {
var check = function (id) {
var element = document.getElementById(id);
str = trim(element.value);
if (str.substr(0, 7) == 'http://') {
element.value = str.substr(7);
}
else if (str.substr(0, 8) == 'https://') {
element.value = str.substr(8);
}
return true;
}
return check('f') && check('fb');
}
this code fragment of your code is unreachable
var fb = document.getElementById('fb')
str = trim(fb.value);
if(str.substr(0, 7) == 'http://'){
fb.value = str.substr(7);
}
else if(str.substr(0, 8) == 'https://'){
fb.value = str.substr(8);
}
return true;
before reaching the above code, the function will already have exited with a return value of true.
One way to do it is as follows (this code will fix both your links and alert true in case both are safe links.
function MakeLinkSafe(linkid){
var f = document.getElementById(linkid)
str = trim(f.value);
if(str.substr(0, 7) == 'http://'){
f.value = str.substr(7); return true;
}
if(str.substr(0, 8) == 'https://'){
f.value = str.substr(8); return true;
}
return false;
}
var f = MakeLinkSafe('f');
var fb = MakeLinkSafe('fb');
if(f&&fb)alert(true);else alert(false);

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

Categories

Resources