Javascript if statement not working ecommerce - javascript

The site I'm working on requires that if the total amount is less than 399 then a delivery fee of 100 is to be charged. However I put:
//<![CDATA[
simpleCart({
if(total<399){shippingFlatRate: 100;}
});
//]]>
the main function has the total amount and that works and flat rate is set on, but when I use this if statement it stays on 0 and doesn't become 100.

If you are trying to set the property of an object then your syntax is wrong. Try this:
shippingFlatRate: total < 399 ? 100 : 0

Seems to be the wrong coded. If you have an object and needs to define a variable with a conditional, you can make this:
simpleCart({
shippingFlatRate: function() {
if(total<399){
return 100; //it takes 100 of value
} else {
return 0; // it takes 0 of value
}
}
});

Related

Get a specific percentage chance of running something?

I read some threads on the site about getting percentages of running a function, but none of them guide me how to get a specific decimal percentage of running a function.
I tried something like:
Math.floor(Math.random() * 100) + 1 + '%'
However it doesn't return decimals.
What i'd like is for it to let's say, have a 0.5% / 100% chance of running console.log("0.5%"), is there any way to do this? Thank you very much!
Math.random() returns a random number between 0 and 1.
A percentage is just a fraction out of 100. Divide by 100 to get a number between 0 and 1.
So, to get a block of code that runs a certain percentage of the time, take the desired percentage, divide it by 100, and run the code if a random number is less than it.
if( Math.random() < 0.5/100) {
/* code that runs 0.5% of the time */
}
Here is what you are asking for.
The percentageFromRandom is explained in my comment above.
The runWithProbability function calls a given function with a certain probability, when this function is called.
The logWithProbability uses the runWithProbability function, but with the custom console.log functionality as your answer question for.
The init function shows an example of usage of the function, by running it 30 times with 30 random probability. In most cases it would log the larger %'s as they are more likely to have the console.log function be called.
//convert the random value into human readable percentage
function percentageFromRandom(value, fractionalDigits = 2){
return (value*100).toFixed(fractionalDigits)+'%';
}
//take a function and probability of running it
//if the probability is met, call the function.
function runWithProbability(fn, probability){
if(probability >= 1 || Math.random() < probability){
return fn(probability);
}
return false;
}
//make a console log with a certain probability,
//log the percentage probability if called
function logWithProbability(probability){
runWithProbability(()=>
console.log(percentageFromRandom(probability))
, probability);
}
// See console logs and their probability as
// a percentage of running.
const init = () => {
for(let i = 0; i < 30; i++){
logWithProbability(Math.random());
}
}
init();
The issue with the Math.floor(Math.random()) example is that Math.floor() removes all of the fractional values of a number. To get precision to a certain fixed point, multiply by the maximum whole number wanted, then adjust to a fixed decimal.
for (var i = 0; i < 10; i++) {
var num = 10 * Math.random(); // Max 10.000...
console.log(num, num.toFixed(1) + '%') // Fix (and round) the first decimal
}

vue.js pagination mis calculation

In my app, I have some pagination code which calculates the pagination based on data from a REST API. When I add the page of pages, it is calculating from page 0 not from 1, so it says 0 of 9 and when it gets to the end it says 8 of 9, when it should say 1 of 9 and 9 of 9 at the end. So far my code is:
HTML
<p>Page {{page}} of {{pageCount}}</p>
JS
data: function() {
return {
page: 0
};
},
computed: {
pageCount() {
let l = this.result.length,
s = this.size;
return Math.floor(l / s);
},
paginated() {
const start = this.page * this.size,
end = start + this.size;
return this.result.slice(start, end);
}
},
Any ideas? Maybe I am calculating the math.floor method wrong?
Your page variable is 0 indexed instead of 1 index. You can keep it this way so that your pagination continues to work as intended, but where you are outputting it to the user you can simply add 1 so it makes sense to a user.
<p>Page {{page + 1}} of {{pageCount}}</p>
From what I understood, your pageCount() method is correct because you indeed have 9 pages so math.floor is not the problem, your page variable is the one that is incorrect but I cannot see where you are getting that variable from but a simple yet coarse solution would be just to add 1 to the variable.

Finding the smallest multiple

I'm trying to learn and practice javascript on my own and I've made a bit of progress but I can still get stuck with elementary problems. I think my code is really close to giving me the correct answer but I fail to see what issue I'm missing. If someone better at coding would please take a second and fill me in on what logic error I have, I would be greatly appreciative!
<script>
//2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
var input = 11;
function smallestMultiple(){
for(var i = 2; i <= 10; i++){
if(input % i === 0 && isDivisible(input))
alert(input);//this should only alert when input is divisible by all numbers between 2 and 10
}else{
input ++;
//if input isn't divisible by all numbers between 2 and 10, increment input by 1
}
}
};
// The following function should return true when "input" is divisible by 10, which is the trigger for alerting "input"
function isDivisible(input){
if(input % 10 === 0){
return true;
}else{
return false;
}
};
smallestMultiple();
</script>
Your script is going to find the smallest integer that's divisible both by 10 and a number in 2,3,...,9, which is not what you need.
The faster implementation would probably be setting a couple of temporary divisors that shrinks until the left edge surpass the right one ...
The simplest instead is just selecting a number in 1,2,3...,9, then try to divide it for every number in 1,2,3...,9
The following html sandbox (to remain on-topic) would probably help you to understand.
<html>
<head>
<meta charset="utf8">
</head>
<body>
<div>
<p class="output"></p>
</div>
<script>
window.onload = function() {
function smallest_shared_multiple(from, to) {
var tmp_divisor = from
var tmp_candidate = tmp_divisor
for(;tmp_divisor < to +1;) {
if (tmp_candidate % tmp_divisor) {
tmp_divisor = from
tmp_candidate++
} else {
tmp_divisor++
}
}
return tmp_candidate
}
document.querySelector('p.output').innerHTML =
'For the given range, the smallest shared multiple is ' +
smallest_shared_multiple(1, 10)
}
</script>
</body>
</html>
edit: Please, consider to indent your code before posting. Moreover, as a general rule of programming, it's better naming functions in way that's evocative to what they're supposed to do. ..and make variables' scope the smallest you can. :)

Check/eliminate different row/columns in Backtracking function javascript

I have this code to solve a 3x3 sudoku (Only rows/columns are need to be checked, there can be 4 of the same numbers in one block, for example this is a good one:
123
231
312
)
I have the function fillsquare, with input an array [[1,2,0],[0,3,1],[3,0,2]] where the 0 need the be changed to the right number.
function fillsquare(square){
for (var a = 0; a<4; a++){
for (var b = 0; b<4; b++){
if (square[a][b] === 0){
// do the function to check whether I can enter the right number
}
else {
// ?????????????????????
}
}
}
}
According to my professor, it should be a recursive code, but I dont think this is recursive, anyways this base will work.
I still need to change the 0's to the number that fits in place.
I have a small clue how to do this with bruteforce/backtracking, but no code to achieve this.
enter 1 in the zero, if there isn't a one in the row or column, continue to the next zero. Else enter 2 and check again etc.
I hope you can help!
PS: My prof. gave me this psuedocode for checking etc.:
function fillSquare(square) {
find first 0 in square
if (there is no 0) {done!}
else {determine every value that can be put on the place with the zero
(check column and row) save them for example in a temprary row
for (every possible value) {
fillSquare(square with value filled in place)
}
}
}
I hope this is a bit clear, it is translated;)

Elegant way to bias random boolean

I'd like to create a random boolean in JavaScript, but I want to take the previous value into account. If the previous value was true, I want it to be more likely for the next value to be true. At the moment I've got this (this is in the context of a closure - goUp and lastGoUp are locals to the containing scope):
function setGoUp() {
goUp = getRandomBoolean();
if(lastGoUp) {
goUp = getRandomBoolean() || goUp;
}
else {
goUp = getRandomBoolean() && goUp;
}
lastGoUp = goUp;
}
So, the algorithm goes:
Get a random boolean
If the random boolean from the previous call was True:
a) get another random boolean, and or these two together
b) else get another random boolean and and these together.
I'm sure this algorithm could be simplified. I wondered about doing:
if(lastGoUp && goUp) {
goUp = goUp * (getRandomBoolean() || goUp);
}
but that seems really dirty.
There's also a problem with this algorithm which means that I can only double the chance of getting the same boolean again - I can't tweak it easily. Any ideas?
You should define the distribution you want, but maybe you are looking for the following?
if (lastGoUp) {
goUp = Math.random() < 0.8;
} else {
goUp = Math.random() < 0.2;
}
Instead of getting a random boolean, get a random number, say between 0 and 99. Keep a threshold value instead of the last number, and adjust the threshold according to the result:
var threshold = 50;
function setGoUp() {
goUp = getRandomNumber() < threshold;
threshold += goUp ? -10 : 10;
}
This would keep a running tab, so if you get consecutive results that are the same, the probability would keep falling for that result.
If you only want to consider the last result, you would instead set the threshold to a specific value:
threshold = goUp ? 40 : 60;
If you only want the probability of the next event to depend on the current value, and not the history of values up til now, what you want is called a Markov process. Often these are implemented with a 2D table of probabilities that you look up (prob of each next outcome given current one), but for a simple bool-valued event, an if statement is sufficient (see meriton's answer; note that it corresponds to a table of probabilities [0.8 0.2; 0.2 0.8]).
If you want something that gets more likely, say, the more successes you get in a row, then you need to devise a sequence of probabilities for success that perhaps approaches, but does not exceed, 1. There are any number of formulas which can do this, depending on how strong you want the bias to become and how quickly you want it to get there.
I would just make the probability of getting value true be an explicit float variable p. Then I could tweak it easily, by increasing p in some way if I got true last time or by doing nothing with it if I got 'false'.
Can replace Math.random for a better randomizer.
var setGoUp = (function(){
var last;
return function(){
// if last 66% chance for true else 50% chance of true.
return !!(last ? Math.random()*3 : Math.random()*2);
}
}());
!! converts anything to a boolean, 0 = false.

Categories