I have these two buttons, one that calls minus(val) and the other calls plus(val) function.
function minus(val) {
val <= 1 ? width = 1 : width = val - 1;
}
function plus(val) {
val >= 5 ? width = 5 : width = val + 1;
}
Is it possible to combine both these functions into one? So I can just call one function on each button, like changeValue(val);
Thanks in advance.
Is it possible to combine both these functions into one?
No. They do different things, e.g. when you call them with the value 3.
You can see that better if you simplify them to
function minus(val) {
width = Math.max(1, val - 1);
}
function plus(val) {
width = Math.min(5, val + 1);
}
Of course you might use a function with a second parameter that decides what to do. It could be
function changeValue(val, dir) {
width = Math.min(5, Math.max(1, val + dir));
}
that you could call both as changeValue(val, +1) and changeValue(val, -1).
Or right away, with a more descriptive name:
limitedWidth(val) {
width = Math.min(5, Math.max(1, val));
}
// limitedWidth(val + 1)
// limitedWidth(val - 1)
function changeValue(val){
if(val > 5){ };
else if(val < 1){ };
}
Can you get the rest?
Related
I need help creating the code to find the factorial of a number. The task is to
Create a variable to store your answer and initialize it to one
Create a loop that beings at the given value, fact
Check if fact is one or zero
multiply fact with your answer variable
At the end of the loop decrease fact
Print answer using console.log
The pseudocode is
while(factorial)
if factorial == 0 or factorial == 1
break
result => result * factorial
factorial => factorial - 1
My code below isn't complete because I'm confused by the pseudocode.
function nth_fact(nth){
var a = 1
while(nth_fact)
if (nth_fact == 0 || nth_fact == 1){
break;
result => result * nth_fact
nth_fact => nth - 1
console.log()
}
}
At first lets examine what went wrong:
var a = 1
What is a? Its definetly not a good name for a variable. Maybe name it to result ? The same applies to nth which should be named factorial and nth_fact which should rather be factorize or sth. You should also always use ; to end a statement.
while(nth_fact)
As your while loop contains multiple statements (the if and the two assignments) you need to open a block here by using { right after the condition. nth_fact refers to the function, you rather want to take factorial here.
if (nth_fact == 0 || nth_fact == 1){
break;
Now you open a block statement for the if, but you never close it. So you need another } after the break.
result => result * nth_fact
nth_fact => nth - 1
console.log()
=> is the arrow function expression, but you want the assignment operator =. Also you need to pass something to console.log, e.g. console.log(result)
All together:
function factorize(factorial){
var result = 1;
while(factorial){
if (factorial == 0 || factorial == 1){
break;
}
// ?
factorial = factorial - 1;
console.log(result);
}
return result;
}
That pseudocode is indeed confusing, because what it calls factorial is actually not the factorial -- it's the current value, which the result (which is actually the factorial we're looking for) is multiplied by. Also, if is superfluous, because while already checks for the same condition. So the correct pseudocode would be
currentValue = argument
factorial = 1
while (currentValue > 1)
factorial = factorial * currentValue
currentValue = currentValue - 1
// now, 'factorial' is the factorial of the 'argument'
Once you get this sorted out, here's a bonus assignment:
create a function range(a, b) that creates an array of numbers from a to b. For example, range(5, 8) => [5, 6, 7, 8]
create a function product(array) that multiples array elements by each other. For example, product([2, 3, 7]) => 42
write the factorial function using product and range
I solve this this way
function factorial(number) {
let num = 1;
let result = 1;
while (num <= number) {
result = result * num;
num++;
}
return result;
}
const myNumber = factorial(6);
console.log(myNumber);
function factorial(num) {
var result = 1
while (num) {
if ((num) == 0 || (num) == 1) {
break;
} else {
result = result * num;
num = num - 1;
}
}
return `The factorial of ${val} is ${result}`
}
let val = prompt("Please Enter the number : ", "0");
var x = parseInt(val);
console.log(factorial(x));
A Short And Clean Code is :
let number = 5;
let numberFactorial = number;
while(number > 1){
numberFactorial = numberFactorial * (number-1);
number--;
}
console.log(numberFactorial);
function factorize(factorial) {
if(factorial == 0 | factorial == 1) {
return 1
}
else{
var result = factorial;
while(factorial >= 1 ){
if(factorial-1 == 0) {
break
};
result = result * (factorial - 1);
factorial = factorial-1;
//DEBUG: console.log(factorial + ' ' + result);
};
return(result);
}
}
If you want more info about functions, can see in my GitHub, good learning!
Github: https://github.com/bennarthurdev/JavaScript/tree/main/FUNCOES
You used the right approach. Just the syntax was wrong. Here it is:
function nth_fact(nth){
var result = 1 ;
while(nth){
if ((nth) == 0 || (nth) == 1)
break ;
result = result * nth;
nth = nth - 1
}
console.log(result);
return result;
}
I'm doing a memory game and I need to don't repeat the same picture more than twice, so I made a random number generator that repeats till the number isn't in an array. Doing that makes so many requests, so, when repeating the code, it doesn't work so I can't make the second half of the game. I know that the problem is in that because, when making it return the result without checking if it isn't in the array, everything works (but the images repeat, obviously). So, how can I make a function that gives a random number between two values that isn't in an array? I hope this is easy to understand.
Here the function:
function thingForTest() {
let forTest = randomBetweenBut(1, 8, 0);
if (array.includes(forTest)) {
return thingForTest();
} else {
return forTest;
}
}
Here the entire code:
var array = [];
function randomBetweenBut(num1, num2, but) {
function ifThing(num1, num2, but) {
let result = parseInt(Math.random() * (num2 - num1 + 1), 10) + num1;
if (result != but) {
return result;
} else {
return ifThing(num1, num2, but);
}
}
return ifThing(num1, num2, but);
}
function pictureRandomizer() {
for (let i = 1; i < 17; i++) {
let r1;
let picture = document.createElement("img");
function thingForTest() {
let forTest = randomBetweenBut(1, 8, 0);
if (array.includes(forTest)) {
return thingForTest();
} else {
return forTest;
}
}
array.push(thingForTest());
picture.src = "img/" + array[i - 1] + ".jpg";
let cuadrado = document.getElementById("cuadrado-" + i);
cuadrado.appendChild(picture);
if(i == 16 && r1 == false) {
i = 1;
r1 = true;
} else {
r1 = false;
}
}
}
pictureRandomizer();
You can use a function like this to return a random number between a min and a max, excluding any number passed in the exclusionArray. No recursion needed! It also includes a clause to stop infinite loops when a complete exclusionArray is passed.
Should be noted that since we're rerolling a random function, this could loop infinitely if you got REALLY unlucky, so this may not be the best function if your min, max and exclusionArray length are in the millions; But for most applications this should get the job done.
const getRandomWithExclusion = (min, max, exclusionArray) => {
// if exculsionArray contains all possible integers, return null to avoid infinite loop
if (exclusionArray.length > max - min) return null;
let output = null;
// if the randomly generated number is in the exclusionArray, reroll
while(output === null || exclusionArray.includes(output)) {
// simple random range function
output = Math.round(Math.random() * (max - min) + min);
}
return output;
}
.....
I'm doing a kata on Codewars. I'm supposed to write a function that returns the index of which number, is not like the others, in evenness(i.e. [1, 2, 4] should return 0). I believe I have a solution, and it proves true when copy/pasting the code, and console.logging on freecodecamps live server, however, when i try to run the code where it is written, it only passes one test. What is going wrong here?
I've tried testing with console.logs, and my solution holds. I know I could just use filter to solve the problem, but i wan't to practice fundamentals.
let odd = [];
let even = [];
function isEven(num) {
if (num % 2 === 0) {
return true;
} else {
return false;
}
}
function iqTest(numbers) {
let nums = numbers.split(' ').map(function(item) {
return parseInt(item, 10);
})
for (let i in nums) {
if (isEven(nums[i])) {
even.push(nums[i])
} else {
odd.push(nums[i])
}
}
if (even.length > odd.length) {
return nums.indexOf(odd[0]) + 1;
} else {
return nums.indexOf(even[0]) + 1;
}
}
The function should accept a string of numbers, one of which will not be either even or odd, then return the index of that number + 1.
You could take the in comments mentioned approach and search for at least one odd and one even and one additional item, at least three items and exit early if this combination is found.
No need to convert the values in advance, because the value get converted to number by using the remainder operator of isEven function.
For a faster return value store the index instead of the value and omit a later indexOf seach.
function isEven(i) { return i % 2 === 0; }
function iqTest(numbers) {
var even = [], odd = [], values = numbers.split(' ');
for (let i = 0; i < values.length; i++) {
(isEven(values[i]) ? even : odd).push(i);
if (even.length && odd.length && even.length + odd.length > 2)
return (even.length < odd.length ? even : odd)[0] + 1;
}
}
console.log(iqTest("1 2 4")); // 1
console.log(iqTest("2 4 7 8 10")) // 3
console.log(iqTest("1 2 1 1")); // 2
Hi there I have been researching and trying to learn how to check for the time complexity of certain algorithms. I've seen this video which was very helpful.
That being said I wondered off and started trying to work out the Worsts Case and an average case of certain algorithms.
1
I believe in the following snippet it is O(n) since to ind the value for sin we have to loop the entire array.
function mySin(x, iterNum) {
var mxx = -x*x;
var sin = 1;
var n = 0;
var term = 1;
for (var i = 1; i <= 2*iterNum; i++) {
n = n + 2;
term = term * mxx / ( n*(n+1) );
sin = sin + term
}
sin = x*sin;
console.log(sin + " = my function.");
console.log(Math.sin(x) + " math.sin");
}
Thanks again
2
function calculateFibonacciSum (num) {
if(cachedNumbers[num]) {
return cachedNumbers[num];
}
if(('number' === typeof num) && num <= 0) {
throw new Error ('Fibonnci series starts with 0. Please, enter any interget greater than or equal to 0');
}
else if(('number' === typeof num) && num === 0) {
return 0;
}
else if(('number' === typeof num) && (num === 1 || num === 2)) {
return 1;
}
else {
var value = calculateFibonacciSum(num-1) + calculateFibonacciSum(num-2);
cachedNumbers[num] = value;
return value;
}
}
While for this one I think it is also O(n) since in the first if/else statement the tc is O(1) since its contestant whilst the final else statement we must loop all the numbers and if the number is not calculated then call the function again (aka recurssion).
TIA
Both of these seem correct to me. Here's a bit more explanation:
1.
This is in fact O(n), as there are n iterations of the loop, the rest constant time; and n is proportional to iterNum
2.
This one is also linear time, but only since you cache the results of previous calculations. Otherwise it would be O(2n).
It is linear time since it essentially runs a loop down to the base cases (0 and 1). In fact, you could re-write this one using a loop instead of recursion.
https://github.com/maranomynet/linkify
I'm using this plugin. It works, and everything's fine. But is there an option I can plug into it so that if the url length is longer than "X", then truncate it, and add "..."?
Right now the URLs are so long.
I notice in the demo there is a "handleLinks" callback function, but how do I use that?
You're right, you can use handleLinks callback function. For example I wrote simple functional that you need:
handleLinks: function (links) {
for (var i = 0, cnt = links.length, tmpLink; i < cnt; i++) {
tmpLink = links[i].innerHTML;
if (tmpLink.length > 10) {
links[i].innerHTML = tmpLink.substr(0, 10) + '...';
}
}
}
It truncates links if they longer than 10 characters. You can modify this script by your needs.
For URL truncating I choose to shorten in the middle, as the domain and file are usually more important than the directory path.
Taken and adapted for this question from my GitHub fork of Andrew Plummer's JavaScript Library Sugar.
String.prototype.shorten = function(length, position, countSplitter, splitter) {
if (this.length < 1 && length < 1) return String(this);
if (!(typeof(splitter) === 'string')) splitter = '...';
if (!(typeof(countSplitter) === 'boolean')) countSplitter = true;
var balance = (countSplitter) ? splitter.length : 0;
if (length <= balance || this.length <= length) return String(this);
// Perform shortening
var shortened, beforeSplitter, afterSplitter;
if (position == 'left') {
afterSplitter = this.substring(this.length - length + balance, this.length - 1);
shortened = splitter + afterSplitter;
} else if (position == 'right') {
beforeSplitter = this.substring(0, length - balance);
shortened = beforeSplitter + splitter;
} else {
beforeSplitter = this.substring(0, Math.ceil((length / 2) - (balance / 2)));
afterSplitter = this.substring(this.length - Math.floor((length / 2) - (balance / 2)), this.length);
shortened = beforeSplitter + splitter + afterSplitter;
}
return shortened;
}
Example of shortening a Url so the resultant string is 20 characters long:
var toShorten = 'http://stackoverflow.com/questions/9156458/when-using-jquery-linkify-plugin-how-do-i-truncate-the-url';
var shortened = toShorten.shorten(20); // Output: 'http://st...-the-url'
Note: this code has only been proof read and not unit tested. The Sugar implementation has been unit tested, however.