How to write a script that will calculate an interest rate - javascript

I am building a form using the WP plugin called Calculated Fields Form.
The first question is for people to enter the amount they want to invest (fieldname2)
The second question is for people to select the number of months (fieldname3)
Based on the amount and the length, a different interest rate should be displayed.
I am supposed to enter the equation myself so I wrote the following script to try but it doesn't work.
(function()`{`
if (50<=fieldname2<=99 && fieldname3=3) return fieldname2*4/100;
if (50<=fieldname2<=99 && fieldname3=6) return fieldname2*6/100;
if (50<=fieldname2<=99 && fieldname3=12) return fieldname2*8/100;
`}`)();

It's a little unclear what you are trying to achieve here but the issues with your code are as follows:
(function()`{`
// --------^^^ unexpected template string
if (50<=fieldname2<=99 && fieldname3=3) return fieldname2*4/100;
// ------^^^ this is not valid ----^^^ should be === not =
if (50<=fieldname2<=99 && fieldname3=6) return fieldname2*6/100;
if (50<=fieldname2<=99 && fieldname3=12) return fieldname2*8/100;
`}`)();
// immediately invoked function - but why?
// what happens if "50<=fieldname2<=99" is not satisfied?
A bit of advice - write the function first as a testable entity to see if it is even getting the result you want. Use expressive arguments so you can reason about what you are doing. Consider cases that are not covered by your function (see comments below). In those cases, you will return undefined which I doubt is desirable.
function calculateInterest (amount, months) {
if (50 <= amount && amount <= 99) {
if (months === 3) return amount*4/100;
if (months === 6) return amount*6/100;
if (months === 12) return amount*8/100;
// what should we return if months does not satisfy one of the above?
}
// what should we return if amount does not satisfy the above?
}
Assuming fieldname2 and fieldname3 are variables that exist in your code, you can now call the function calculateInterest(fieldname2, fieldname3)

Related

Is there a way to test multiple integers as "correct" in JavaScript for the entire function to pass as correct?

I have a class assignment in which I must create a function that tests 4 integers for a combination lock. For example, let's call the parameters a, b, c, and d. In the function :
a can be 3, 5, or 7
b must be 2
c can be anywhere between 5 and 100, including 5 & 100
and d can be less than 9 or more than 20, but neither 9 not 20 will work
The function must test all of these numbers as "correct" for the combination to be correct. I've used switch statements to get the numbers to return properly, but is there a way I can test for all 4 numbers at once and for the code to stop when it reaches an incorrect number?
I tried something like the code below, but it returned as undefined. Probably because it is long and nonsensical.
checkLock = function(a,b,c,d) {
if (a === 3 || 5 || 7 && b === 2 && c >= 5 || c <= 100 && d < 6 || d >
20) {
return "correct";
} else {
return "incorrect";
}
};
I've tried using some switch statements and alternating if..else statements. But it doesn't catch incorrect combinations.
I've looked at these resources on W3 Schools about switch statements, this article about nesting if...else statements, and articles from Front Stuff and other stack overflow questions to try and figure it out. I'm at a brick wall now.
Since this is for a class assignment, I won't give you the code. Instead I will give you a hint.
Your if statement is invalid.
a === 3 || 5 || 7
You need a left hand assignment for the 5 and 7:
a === 3 || a === 5 || a === 7
You could also return early by first checking a. Something like:
if (a !== 3 && a !== 5 && a !== 7) {
return 'incorrect'
}
This way would make the code neater, and the code after that would be simpler since you now know that a is correct.

Good way to obfuscate Javascript code in Gulp [duplicate]

This question already has answers here:
How can I obfuscate (protect) JavaScript? [closed]
(22 answers)
Closed 3 years ago.
This question knowing that obfuscation is by no means a strong way to protect code...
Using Gulp, I'm looking for a way to prevent my app's content to appear in a too obvious manner. Not manipulating sensitive data, but I'd still not want my minified code to look too obvious to modify.
Been trying gulp-minify and gulp-uglify, but either my use of them is wrong, either they don't fill my need.
Needs being:
- function renaming
- variable renaming
- string obfuscation (at least prevent the string from being human readable at first glance)
- not more than 2x the storage needs
What would be the suggested approaches, leads, plugins?
Thanks in advance,
Just try this: Javascript Obfuscator.
As far as I know, it's almost impossible to revert the obfuscated code back to the original.
So far, the most effective (in my case) is to pipe the following code, which just applies character rotation:
function obfuscate(text, key, n = 126) {
// return String itself if the given parameters are invalid
if (!(typeof(key) === 'number' && key % 1 === 0)
|| !(typeof(key) === 'number' && key % 1 === 0)) {
return text.toString();
}
var chars = text.toString().split('');
for (var i = 0; i < chars.length; i++) {
var c = chars[i].charCodeAt(0);
if (c <= n) {
chars[i] = String.fromCharCode((chars[i].charCodeAt(0) + key) % n);
}
}
return chars.join('');
},
function defuse(text, key, n = 126) {
// return String itself if the given parameters are invalid
if (!(typeof(key) === 'number' && key % 1 === 0)
|| !(typeof(key) === 'number' && key % 1 === 0)) {
return text.toString();
}
return obfuscate(text.toString(), n - key);
}
You may want to consider gulp-javascript-obfuscator. It's a node module and version ^1.1.5 worked very well for me. It also has the option to minify with the following code:
// Imports ...
obfuscator = require('gulp-javascript-obfuscator')
// ... Other code
gulp.src('my_file.js')
.pipe(obfuscator({compact:true}))
.pipe(gulp.dest('dist'));

Using jquery to show div if all above value's in form are true to criteria

For the most part I have this code working. I originally had it so that if the email field length was greater than 10 then on keyup a div below would show. That worked okay. However, I want to add more validation. Below is my jQuery and I'm not sure I'm using the correct syntax.
$('#primaryemail').keyup(function(){
if($(this).val().length > 11 && ('#first_name').val().length > 6 && ('#phone_number').val().length == 10)
$('#projectinfo').show();
else
$('#projectinfo').hide();
});
I'm sure where I went wrong is with the && operators getting that from JavaScript and not entirely positive this is the correct way with jQuery.
Originally I had just the primaryemail as the validation but then added the first_name & phone_number as well. Once I added that it didn't work.
It might help to check your syntax and break it to multiple lines:
$('#primaryemail').keyup(function(){
if(
$(this).val().length > 11 // I suggest you also use .trim()
&& $('#first_name').val().length > 6
&& $('#phone_number').val().length == 10
) { // Always helpful to use Brackets
$('#projectinfo').show();
} else { // Especially around 'else'
$('#projectinfo').hide();
}
});
My suggested alternative is this:
// Cache your variables, noting the comma at the end of the first
// three lines, and the semicolon at the end of the 4th one.
// If you add more, use a comma after each one except the last one.
var $firstName = $('#first_name'),
$primaryEmail = $('#primary_email'),
$phoneNumber = $('#phone_number'),
$projectInfo = $('#projectinfo');
// Now bind your event listeners
// and use a simple function name to keep it easy!
$primaryEmail.keyup(function(){
if(isValidData()) {
$projectInfo.show();
} else {
$projectInfo.hide();
}
});
// Create a function for your logic that return a simple Boolean
// This keeps your state checking separate from your actions
// which rely on that state. You may check states in multiple places
// so it might be helpful to put them in separate functions to avoid
// repetition in the future.
function isValidData(){
return (
11 < $primaryEmail.val().trim().length
&& 6 < $firstName.val().trim().length
&& 10 == $phoneNumber.val().trim().length
);
}

Working With ifNan Function

I'm having trouble getting the Codecademy section of ifNan done. How do I make it so the ifNan function checks the number I manually input at the end when I run the function. For example:
var isEven = function(number) {
if (number % 2 === 0) {
return true;
} else if (isNan(number)) {
return "Your input is not a number!";
} else {
return false;
}
};
isEven(2);
What would I put in the isNan function so that when I input the number at the bottom it also checks if it is actually a number?
you could condense that down to:
function isEven(number)
{
if(!isNaN(number) || number % 2 === 0)
{
return true;
}
return false;
}
See elclanrs comment. isNan is not a function isNaN is. caps matter there.
So...update to this long-standing issue:
I went back to codecademy and restarted the lesson. After researching for about a week, and a good long breather, I came back to this frustrating issue and even then found myself writing the same exact code that I had in the beginning of this issue (because I knew it was correct).
You all made valid points.
Dennis you're absolutely right this can be condensed in a few areas but Codecademy is very rigid (which I'm liking less and less) so it would have never let me pass the dang section.
Anyways, I wanted to close this but "answer" (kind of) it first.
Thanks for all your assistance.
Try this:
var isEven = function(number) { if (number % 2 === 0) { return true; } else if(isNaN(number) === true || false){ return "your input is not a number"; } else { return false; }// Your code goes here!
}; isEven("Gbemi")

Javascript (-1 <= 5 <= 1) === true?

I want to validate that a given number is within a given range:
function validate(min, max, amount) {
return (min <= amount <= max);
}
But this does not seem to work properly. I know I can do it with two comparison and a logical AND, but I would like to it in one comparison. Is there any NATIVE javascript way to realize this?
Use this instead :
return (min <= amount && amount <= max);
There is no shortcut. And there is a good reason the JavaScript engine can't guess your intent : what you typed was valid, it just isn't interpreted as you'd like. You were testing, in fact
((min <= amount) <= max)
and the result of the first comparison, which is a boolean, is converted to 0 or 1 for the second one (more details here about operators precedence, those comparison operators are left-to-right).
If you really want a shortcut, you could do this :
Number.prototype.isin = function(m,M) {
return m<=this && this<=M;
};
console.log(0.5.isin(1,2)); // logs false
console.log(3..isin(2,5)); // logs true
but I personally would use the standard solution with && that everybody can read and which doesn't involve an additional function call.
Aside : I could have called my function in instead of isin but it might break ES3 browsers.
Operators ( == , <= , < , >= , == ) take only 2 arguments.
When there are more arguments it uses mathematical order of computing. So in fact your code behave like:
min <= amount // true
true <= max // this is illogical
It's also optimal, because when executing logical statements and finding something like:
if(false && (some computing))
It will ignore (some computing) because result will be always false
This is very common practive in every language. Test like this will not have NullPointerException error, because first argument is already false.
if(obj != null && obj.getValue() > 10) //C++,Java, etc.
if(obj !== undefined && obj.val() > 10) // javascript
if(obj.length != 0 && obj.val() > 10) //jQuery

Categories