Calling multiple functions to one value in javascript - javascript

Probably an beginner question. When a counter I have on my page hits 10000 I am looking to reset the number to 1 and show "+10k" next to it.
For example, if the counter response was 10010 it would display as follows:
Image of UI
Is there a more efficient way of doing the following:
Set one ID to reset the number to 1 when it hits 10000
Change the display settings of another ID when API response value hits 10000
// below changes 10000 to 1
function kFormatter(num) {
if (num > 1 && num < 10000) {
return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-0).toFixed(1)): Math.sign(num)*Math.abs(num)
}
else if (num > 10000 && num < 20000) {
return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-500).toFixed(1)): Math.sign(num)*Math.abs(num)
}
}
// Below script shows +10k copy
function show10k(num) {
if (num > 1 && num < 10000) {
document.getElementById("10k-text").style.display = "none";
}
else if (num > 10000 && num < 20000) {
document.getElementById("10k-text").style.display = "flex";
}
}
// output
function websiteVisits(response) {
document.querySelector("#visits").textContent = (kFormatter, show10k)(response.value);
}

I'm not sure of the constraints of your project but this is how I would achieve the same thing:
if (input.value > 10000) {
let tenKays = Math.floor(input.value / 10000)
let digits = input.value % 10000
output.innerHTML = digits + " " + "+" + tenKays + "0K"
} else {
output.innerHTML = input.value
}
It could be polished in different ways to display the actual output in a more sophisticated way but it's a simple method that handles numbers of any size.

first : function kFormatter(num) of you is wrong :
(Math.abs(num)-500) should change to (Math.abs(num)-10000)
(kFormatter, show10k) is returned show10k (document):
(kFormatter, show10k)(response.value) <=> show10k(response.value)
You can call 2 function same as :
document.querySelector("#visits").textContent = kFormatter(response.value);
show10k(response.value)
or call show10k() in kFormatter() same as :
function kFormatter(num) {
if (num > 1 && num < 10000) {
show10k("none")
return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-0).toFixed(1)):
Math.sign(num)*Math.abs(num)
} else if (num > 10000 && num < 20000) {
show10k("flex")
return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-10000).toFixed(1)):
Math.sign(num)*Math.abs(num)
}
}
// Below script shows +10k copy
function show10k(display) {
document.getElementById("10k-text").style.display = display;
}
Example :
const valueInput = document.getElementById('number');
const formatNumber = (value) => {
return parseInt(value)
}
valueInput.addEventListener('input', function() {
valueInput.value = formatNumber(this.value);
websiteVisits(this.value)
});
const kFormatter = num => {
let visit = num%10000
let xk = parseInt(num/10000)
showxk(xk)
return visit
}
// Below script shows +10k copy
const showxk = xk => {
let xkEle = document.getElementById("xk-text");
if (!xk) {
xkEle.classList.add('hide')
} else {
xkEle.classList.remove('hide')
xkEle.textContent = (Math.sign(xk) > 0 ? '+' : '') + xk + '0k'
}
}
const websiteVisits = value => {
document.querySelector("#visits").textContent = kFormatter(value)
}
.hide {
display:none;
}
<span id="visits"></span><sup id='xk-text' class="hide"></sup>
<hr />
<input type="number" id="number" step="1">

Related

Countdown from 100 to the number (N) and separate even and odd numbers. Show even numbers in the first line and odd numbers in the second line

<div id="counter">100</div>
<script>
function myFunction() {
var person = prompt("Please enter One number (N) where (N) is a positive integer.", "");
if (person != null) {
document.getElementById("demo").innerHTML =
"Hello " + person + "! How are you today?";
}
}
function countdown() {
var i = document.getElementById('counter');
i.innerHTML = parseInt(i.innerHTML) - 1;
if (parseInt(i.innerHTML) == 95) {
clearInterval(timerId);
}
}
var timerId = setInterval(function () { countdown(); }, 1000);
</script>
<p id="demo"></p>
Example Test Cases:
Input: 10
Output:
100 98 96 94 92
99 97 95 93 91
Another one:
Input: 5
Output:
100 98 96
99 97
I have made my own script which counts down from 100-0, and places each number into an Array variable depending on whether it's Odd/Even.
Here it is:
var even = [];
var odd = [];
var number = 100;
changeNumber();
function changeNumber() {
document.getElementById("counter").innerText = number;
if (checkParity(number) == "even") {
console.log("even");
even.push(number);
} else {
console.log("odd");
odd.push(number);
}
if (number == 0) {
console.log("[Finished]");
console.log("Even numbers:");
console.log(even);
console.log("Odd numbers:");
console.log(odd);
} else {
setTimeout(function () {
number--;
changeNumber();
}, 100);
}
}
function checkParity(n) {
if (n % 2 == 0) {
return "even"
} else {
return "odd"
}
}
<div id="counter">100</div>
I hope that can help.
(function () {
const input = prompt("Please enter One number (N) where (N) is a positive integer.", "");
let count = 100;
if (isNaN(input) || input < 1) return;
const inerval = setInterval(() => {
count--;
if (count % 2 == 0) {
console.log('This is even Numbers ' + count);
} else {
console.log('This is odd Numbers ' + count);
}
if (input == count) return clearInterval(inerval);
}, 1000);
})();
I think this is a possible solution, without many changes to your original code:
<div id="counter">100</div>
<p id="results"></p>
<script>
var input = parseInt(prompt("Please enter One number (N) where (N) is a positive integer.", ""));
var half = parseInt(input / 2);
var i = document.getElementById('counter');
var res = document.getElementById('results');
res.innerHTML += "Even: ";
if (parseInt(i.innerHTML) % 2 == 0) {
res.innerHTML += i.innerHTML;
input--;
}
function countdown() {
if (input == 0) {
clearInterval(timerId);
return;
}
if (input == half) {
var newValue;
if (input % 2) {
newValue = parseInt(i.innerHTML) + input * 2 - 3;
}
else {
newValue = parseInt(i.innerHTML) + input * 2 - 1;
}
i.innerHTML = newValue;
res.innerHTML += "</br> Odd: ";
}
else {
i.innerHTML = parseInt(i.innerHTML) - 2;
}
res.innerHTML += " " + i.innerHTML;
input--;
}
var timerId = setInterval(function(){ countdown(); }, 1000);
</script>
<p id="demo"></p>
Basically you decrease it by 2 till you reach the half, then you go back to the start - 1, looping through the odd numbers (or even, if the counter value was odd at first).

JavaScript Recursive function return undefined instead of an array

I have the next function:
function solveSudoku(prev_tab, fila, columna) {
let tab = _.cloneDeep(prev_tab);
let sig_fila = fila;
let sig_col = columna;
if (fila === 8 && columna === 8) {
//console.log(tab);
return tab;
}
if (columna === 8) {
sig_col = 0;
sig_fila = sig_fila + 1
} else {
sig_col = sig_col + 1;
}
if ((tab[fila][columna]) !== '') {
solveSudoku(tab, sig_fila, sig_col)
} else {
for (let num = 1; num <= 9; num++) {
if (numeroValido(tab, num, fila, columna)) {
tab[fila][columna] = num;
//tab.toString();
solveSudoku(tab, sig_fila, sig_col)
}
}
}
}
it returns undefined instead of a 2D array, i already try to add return in every recursive call =>
return solveSudoku( tab, sig_fila, sig_col )
but now that doesn't work either
I'm not really familiar with algorithms for solving sudoku, so I don't know if the algorithm below is correct.
But you need to ensure that the result of the recursion is returned. In my update below, I return the first recursive call. In the loop, I only return it if the recursion successfully found a solution, otherwise the loop continues trying other numbers in the column.
function solveSudoku(prev_tab, fila, columna) {
let tab = _.cloneDeep(prev_tab);
let sig_fila = fila;
let sig_col = columna;
if (fila === 8 && columna === 8) {
//console.log(tab);
return tab;
}
if (columna === 8) {
sig_col = 0;
sig_fila = sig_fila + 1
} else {
sig_col = sig_col + 1;
}
if ((tab[fila][columna]) !== '') {
return solveSudoku(tab, sig_fila, sig_col)
} else {
for (let num = 1; num <= 9; num++) {
if (numeroValido(tab, num, fila, columna)) {
tab[fila][columna] = num;
//tab.toString();
let result = solveSudoku(tab, sig_fila, sig_col);
if (result) { // continue searching if the recursion failed
return result;
}
}
}
}
}

JavaScript - Make a variable change every second

Ok, so this is my code:
name: function(gameServer, split) {
// Validation checks
var id = parseInt(split[1]);
if (isNaN(id)) {
console.log("[Console] Please specify a valid player ID!");
return;
}
var name = split.slice(2, split.length).join(' ');
if (typeof name == 'undefined') {
console.log("[Console] Please type a valid name");
return;
}
var premium = "";
if (name.substr(0, 1) == "<") {
// Premium Skin
var n = name.indexOf(">");
if (n != -1) {
premium = '%' + name.substr(1, n - 1);
for (var i in gameServer.skinshortcut) {
if (!gameServer.skinshortcut[i] || !gameServer.skin[i]) {
continue;
}
if (name.substr(1, n - 1) == gameServer.skinshortcut[i]) {
premium = gameServer.skin[i];
break;
}
}
name = name.substr(n + 1);
}
} else if (name.substr(0, 1) == "[") {
// Premium Skin
var n = name.indexOf("]");
if (n != -1) {
premium = ':http://' + name.substr(1, n - 1);
name = name.substr(n + 1);
}
}
and i want to change premium to something like <kraken> and <spy> every second, so that then it changes gameServer.skinshortcut to %kraken and then 1 second later it changes that to %spy... and cycles, How do I do this?
Use setInterval(function, delay in ms)
Try:
Var pre_stat=0;
function tgl_pre()
if (pre_stat=0)
{
pre_stat=1;
//change variable to `kraken`;
}
else
{
pre_stat=0;
//change variable to 'spy';
}
setInterval("tgl_pre()", 1000);
end

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.

more than currency input field

I have this input tag where you put the total of your receipt :
<input type="text" name="currency" id="currency" class="text-input" onBlur="this.value=formatCurrency(this.value);" />
The Javascript is as follows:
<script type="text/javascript">
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) {
num = "0";
}
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num % 100;
num = Math.floor(num/100).toString();
if(cents < 10) {
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
}
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
</script>
Users can only enter receipts more than $10.00 bucks, how can I set that on my script? Also they need to know they can not enter currency less than $10.
From what I can gather from your question I think you are looking for something like this. Basically if we have a valid entry such as $100.00 we continue, return true etc, else if we have something that looks like an int or float we can reformat this and recurse the function, else hint user for of vaild entry
var foo = document.getElementById('foo');
foo.addEventListener('blur', function(e) {
var val = e.target.value;
var err = document.getElementById('err');
var errMsg = 'please enter a value $10.00 or greater';
var patt = /^\$\d+\.\d{2}$/;
var amount = parseInt(val.replace(/\$|\./g, ''));
if (val !== '') {
if (patt.test(val)) {
if (amount < 1000) {
err.textContent = errMsg;
} else {
document.getElementById('suc')
.textContent = 'processing request';
}
} else if (typeof amount == 'number' && !/[a-z]/g.test(val)) {
if (/\.\d{2}/.test(val)) {
e.target.value = '$' + (amount / 100);
} else {
e.target.value = '$' + amount + '.00';
}
arguments.callee(e);
} else {
err.textContent = errMsg;
}
}
});
here is a demo
You can apply a validation function when submitting the form to test if the value is below a threshold, such as:
function validate()
{
value = document.getElementById('currency');
if (value <= 10.00)
{
return false
} else
{
return true;
}
}
You could also apply this to the onblur event, but my preference is to present validation errors when the form is submitted.
It looks like you're trying to parse a string, convert it nicely into dollars and cents, and reject it if it's less than 10. There's a much nicer way to do that:
function formatCurrency(num) {
// Remove the dollar sign
num = num.replace("$", "");
// Change the string to a float, and limit to 2 decimal places
num = parseFloat(num);
Math.round(num * 100) / 100;
// If its less than 10, reject it
if(num < 10) {
alert("Too small!");
return false;
}
// Return a nice string
return "$" + num;
}
At the end, are you trying to return -$99.94 if the number is negative?

Categories

Resources