localstorage variable only writes 0 to index.html - javascript

Hi when I run this block of code, the result of "clickamt" is 0 and it does not increment:
switch (isNaN(incremental) || isNaN(clickamt) || isnull(incremental) || isnull(clickamt) || isnull(curfloat) || isNaN(curfloat)) {
case true:
storage.setItem("clickamt", "0");
clickamt = (parseFloat(storage.getItem("clickamt")).toFixed(1));
storage.setItem("incremental", "1");
incremental = (parseInt(storage.getItem("incremental")));
storage.setItem("curfloat", "0");
curfloat = (parseFloat(storage.getItem("curfloat")).toFixed(1));
break;
case false:
if (clickamt % 1000 === curfloat) {
curfloat = (moneylevels()).toFixed(1);
}
clickamt = ((clickamt + incremental) + curfloat).toFixed(1);
incremental++;
storage.setItem("clickamt", (clickamt));
storage.setItem("incremental", (incremental).toString());
storage.setItem("curfloat", (curfloat).toString());
break;
}
The innerHTML of "clickamt" writes 0 and only 0 to "index.html".
I want "clickamt" of type float to increment by using incremental of type int plus curfloat which is of type float. "curfloat" is incremented by 0.1 per 1000 of "clickamt".
I don't think it's a parsing issue or anything of the sort. When I recoded it once it would just append the float it would increment by to the end of clickamt. This made me think there may be a parsing issue somewhere.
Some outputs I've seen are (0, 0.101011,00.010101,1,11,1111111,1111111111,etc.)

You can check on page load if the value for necessary key exists in localStorage. If the value is missing, then compute and save the new value. You can also have an extra event on which you can override the value of this key, but this will be a user action.
function computeRandomValue() {
var data = ["test", "test1", "test2", "test3", "test4"];
var index = Math.floor(Math.random() * 10) % data.length;
return data[index];
}
function setToLocalStorage(newVal) {
var lsKey = "_lsTest";
localStorage.setItem(lsKey, newVal);
}
function getFromLocalStorage() {
var lsKey = "_lsTest";
return localStorage.getItem(lsKey);
}
function initializePage() {
var _val = getFromLocalStorage();
if (!(_val && _val.trim().length > 0)) {
_val = computeAndSaveNewValue();
}
printValue(_val, "lblResult");
}
function computeAndSaveNewValue() {
var newVal = computeRandomValue();
setToLocalStorage(newVal);
printValue(newVal);
return newVal;
}
function printValue(value) {
var id = "lblResult";
document.getElementById(id).innerHTML = value;
}
(function() {
window.onload = initializePage;
})()

Related

Javascript Create new Number wıth own properties

I want create new number object with own properties from Number.
But when assign a number value to my variable, my variable turn to Number(primitive wrapper object).and loss own properties.How can I prevent this?
Example
class Fnumber extends Number {
value = 0;
[Symbol.toPrimitive](hint) {
if (hint === 'object') {
return this;
}
return this.value;
};
//I don't want use Number.prototype.add method because this effect all Number values.
add = function(...v) {
this.value += Array.prototype.slice.call(arguments).reduce((o, v) => o + v)
}
}
var nmbr = new Fnumber();
nmbr.add(4, 2, 4);
console.log(nmbr); //return a Object
console.log(nmbr + 4); //return 14 is number
nmbr = 14;
console.log(nmbr); //return not a Object its Primative number value
console.log(nmbr + 4); //return 14 a number
nmbr.add(4, 2, 4); //raise error.
When doing nmbr = 14 you assign 14 to nmbr, you are not changing the nmbr.value, you are overwriting the object. Instead call add and use nmbr.value when needed.
class Fnumber extends Number {
value = 0;
add(...v) {
this.value += Array.prototype.slice.call(arguments).reduce((o, v) => o + v)
}
}
var nmbr = new Fnumber();
nmbr.add(4, 2, 4);
console.log(nmbr.value);
nmbr.add(5);
console.log(nmbr.value);
nmbr.value = 25; // assign a value to nmbr.value
console.log(nmbr.value);
If you are not planning on reassigning the object, a good practice is to use const instead of var, see the error below.
class Fnumber extends Number {};
const nmbr = new Fnumber();
nmbr = 14;
I found the solution indirectly.
class Fnumber extends Number {
value = 0;
add(...v) {
this.value += Array.prototype.slice.call(arguments).reduce((o, v) => o + v)
}
}
//temğrary variable description
var _nmbr=new Fnumber();
//Define nmbr variable in global scobe
Object.defineProperty(window,"nmbr",{
enumerable: true,
configurable: true,
get() { return _nmbr; },
set(val) { if (typeof val=="number")_nmbr.value=val; }
});
nmbr=4;
console.log(nmbr+2);//output 6
//still nmbr variable is object,because assigned value to
_nmbr.value with above set method
nmbr.add(4, 2, 4);
console.log(nmbr+2);//output 16

Add Two Number leetcode algo

I was doing following leetCode Problem: https://leetcode.com/problems/add-two-numbers/
And I am not sure why one of my test case is failing
So the question is
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their
nodes contain a single digit. Add the two numbers and return it as a
linked list.
You may assume the two numbers do not contain any leading zero, except
the number 0 itself.
For which I have written following algo
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* #param {ListNode} l1
* #param {ListNode} l2
* #return {ListNode}
*/
const makeLinkedList = (inArr, i) => {
if (i < 0) return null
return { val:inArr[i], next:makeLinkedList(inArr, i-1)}
}
var addTwoNumbers = function(l1, l2) {
let sum = 0
let i = 1
while(l1 || l2) {
if (l1 && l2) {
sum = sum + l1.val*i + l2.val*i
l1 = l1.next
l2 = l2.next
} else {
if (l1) {
sum = l1.val*i + sum
l1 = l1.next
}
if (l2) {
sum = l2.val*i + sum
l2 = l2.next
}
}
i = i*10
}
const sumToString = sum.toLocaleString('fullwide', {useGrouping:false});
return makeLinkedList(sumToString, sumToString.length-1)
};
The reason in the above code I have used while loop instead of recursively calling functions is mainly to make it more optimized.
anyway, For the following input, my test case is failing
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[5,6,4]
i.e my output is coming to be [0,3,NaN,NaN,1] instead of [6,6,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
As a note, leetCode compiler will convert array to linkedlist on input. Can someone help me in figuring out why my input might be failing?
When JavaScript stringifies a number in scientific notation, there will be a + sign for positive exponents. That sequence you see is 1E+30, the NaNs are standing for + and E (because of the reverted order). In fact you could have put a console.log(sum) or console.log(sumToString) and catch the issue without knowing this, just simply seeing what is there.
Not all languages tell you the maximum value they can store without loss in precision, but JavaScript in particular does, Number.MAX_SAFE_INTEGER contains the value 9 007 199 254 740 991 so it is a bit more than 9E+15, far less than 1 + 1E+30 (the longer number).
What you are expected to do is to add the numbers like you have learned in elementary school: add two digits, write one digit, and see if there is an 1 to carry to the next digit-pair you are going to add.
Iterative version:
function makeLinkedList(arr,i){
i=i || 0;
return i<arr.length?{val:arr[i], next:makeLinkedList(arr,i+1)}:null;
}
var addTwoNumbers = function(l1, l2) {
var snt={next:null};
var cur=snt;
var carry=0;
while(l1 || l2 || carry){
cur.next={next:null};
cur=cur.next;
var sum=(l1?l1.val:0)+(l2?l2.val:0)+carry;
if(sum<10){
cur.val=sum;
carry=0;
} else {
cur.val=sum-10;
carry=1;
}
l1=l1?l1.next:null;
l2=l2?l2.next:null;
}
return snt.next;
}
var a=[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1];
var b=[5,6,4];
console.log(addTwoNumbers(makeLinkedList(a),makeLinkedList(b)));
a=[9,9];
b=[1,9];
console.log(addTwoNumbers(makeLinkedList(a),makeLinkedList(b)));
Recursive version:
function makeLinkedList(arr,i){
i=i || 0;
return i<arr.length?{val:arr[i], next:makeLinkedList(arr,i+1)}:null;
}
var addTwoNumbers = function(l1, l2, carry) {
if(!(l1 || l2 || carry))
return null;
carry=carry || 0;
var sum=(l1?l1.val:0)+(l2?l2.val:0)+carry;
return {
val: sum % 10,
next: addTwoNumbers(l1?l1.next:null,l2?l2.next:null,sum>9?1:0)
};
}
var a=[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1];
var b=[5,6,4];
console.log(addTwoNumbers(makeLinkedList(a),makeLinkedList(b)));
a=[9,9];
b=[1,9];
console.log(addTwoNumbers(makeLinkedList(a),makeLinkedList(b)));
Solution for the problem in JavaScript.
var addTwoNumbers = function (l1, l2) {
let reminder = 0;
let l1Node = l1;
let l2Node = l2;
let list = new ListNode(0);
let currentNode = list;
while (l1Node || l2Node) {
const valueL1 = l1Node ? l1Node.val : 0;
const valueL2 = l2Node ? l2Node.val : 0;
let sum = valueL1 + valueL2 + reminder;
reminder = 0;
if (sum > 9) {
reminder = Math.floor(sum / 10);
sum = sum % 10;
}
currentNode.next = new ListNode(sum);
currentNode = currentNode.next;
l1Node = l1Node ? l1Node.next : null;
l2Node = l2Node ? l2Node.next : null;
}
if (reminder != 0) {
currentNode.next = new ListNode(reminder);
currentNode = currentNode.next;
}
return list.next;
};
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
const l1 = new ListNode(2, new ListNode(4, new ListNode(3)));
const l2 = new ListNode(5, new ListNode(6))
const res = addTwoNumbers(l1, l2);
console.log(res);

I want to generate random number in method once which are not same with previous one

I have to change background image in method. Background images are coming from this.items service but when method runs new background image shouldn't be same with previous one.
When I run this method it changes images but new image can be same with previous one. How can I do?
export class GridManager {
changeBackground() {
var x = Math.floor(Math.random() * document.querySelectorAll(".grid-item").length);
if (this.items[x].backgroundImage != "" && this.items[x].backgroundImage != null) {
document.querySelector(".container").style.backgroundImage = `url('${this.items[x].backgroundImage}')`;
}
}
}
You need to check if the value is in the array, if exist remove it or do whatever you need to do
function checkItem(array,checkItem){
for( var i=0;i<array.length;i++){
if(array[i] == checkItem){
var removedItem= array.splice(checkItem,1); // your can remove it
/*or simply do your code here */
}
}
}
There's a lot of solutions, to give you another one not mentioned here, you can do a custom generate random number that excludes the previous index that you got.
something like:
class GridManager {
prevIndex = null;
generateRandom(min, max, excludedIndex) {
var num = Math.floor(Math.random() * (max - min + 1)) + min;
return (num === excludedIndex) ? this.generateRandom(min, max, excludedIndex) : num;
}
changeBackground() {
var x = this.generateRandom(0, document.querySelectorAll(".grid-item").length - 1, this.prevIndex);
this.prevIndex = x;
if (this.items[x].backgroundImage != "" && this.items[x].backgroundImage != null) {
document.querySelector(".container").style.backgroundImage = `url('${this.items[x].backgroundImage}')`;
}
}
}

Sum of range in Javascript in function local variable

I have range function and output functions they works correct,now I want create sum function for using as callbac function in range function,but when some function executed local variable let us say total or sum initialize 0(zero),how can solve this problem?
function range(start,end,callback,step) {
// body...
step=step || 1;
for(i=start;i<=end;i=i+step){
callback(i);
}
}
function output(a) {
// body...
console.log(a);
}
function sum(m){
var total=0;
// some code
}
range(1,5,output);
range(1,5,sum);
function range(start,end,callback,step) {
// body...
var aggregate;
step=step || 1;
for(i=start;i<=end;i=i+step){
aggregate = callback(i, aggregate);
}
}
function output(a) {
// body...
console.log(a);
}
function sum(m, aggregate){
return m + aggregate;
}
range(1,5,output);
range(1,5,sum);
This way you could even do cool stuff like
function conc(m, aggregate) {
return aggregate + m.toString();
}
range(1,5,conc,2); //prints 135
Continuition style code, like you've started it with range(), can get really weird and cumbersome.
And please, please, mind defining your local variables. like i
function range(start,end,callback,step) {
step=step || 1;
for(var i=start; i<=end; i=i+step)
callback(i);
}
function output(...label) {
return function(...args){
console.log(...label, ...args);
}
}
function sum(callback){
var total = 0;
return function(value){
//will log ever intermediate total, because sum() has no way to tell when the sequence is over.
callback(total += +value || 0);
}
}
range(1,5,output('range:'));
range(1,5,sum(output('sum:')));
In this case, I'd prefer using a generator instead, although the higher order functions get obsolete.
function *range(start,end,step) {
step = +step || (end < start? -1: 1);
for(var value = start, count = (end - start) / step; count-- >= 0; value += step)
yield value
}
function sum(iterator){
var total = 0, v;
for(v of iterator) total += +v || 0;
return total;
}
console.log("range:", ...range(1,5))
console.log("sum of range:", sum(range(1,5)))
//just to show that this works with your regular array as well
console.log("sum of array:", sum([1,2,3,4,5]));
//and some candy, as requested by Bergi ;)
//I like to stay with the interfaces as close as possible to the native ones
//in this case Array#reduce
var fold = (iterator, callback, start = undefined) => {
var initialized = start !== undefined,
acc = start,
index = 0,
value;
for(value of iterator){
acc = initialized?
callback(acc, value, index):
(initialized=true, value);
++index;
}
if(!initialized){
throw new TypeError("fold of empty sequence with no initial value");
}
return acc;
}
//and the ability to compose utility-functions
fold.map = (callback, start = undefined) => iterator => fold(iterator, callback, start);
console.log(" ");
var add = (a,b) => a + b; //a little helper
console.log('using fold:', fold(range(1,5), add, 0));
//a composed utility-function
var sum2 = fold.map(add, 0);
console.log('sum2:', sum2( range(1,5) ));
Clearly a range function should not take a callback but be a generator function in modern JavaScript, however you were asking how to write such a callback.
You've already tagged your questions with closures, and they are indeed the way to go here. By initialising a new total within each call of the outer function, you don't need to worry about how to reset a global counter.
function makeSum() {
var total=0;
return function(m) {
total += m;
return total; // so that we can access the result
}
}
var sum = makeSum();
range(1, 5, sum);
output(sum(0));
Won't simply calling the callback on the range array suffice if the callback is not undefined? Like this:
> function range(n, callback) {
const r = [...Array(n).keys()]
if (callback) {
return callback(r)
}
return r
}
> function sum(arr) {
return arr.reduce((a, b) => a + b, 0)
}
> range(10)
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
> range(10, sum)
> 45

Unique number counter function?

This undoubtedly already exists but I can't find it anywhere after 20 min of looking.
All I want is a function that counts up so the first time you call uniqueNum() it returns 0, then 1, then 2 etc.
function uniqueNum(){
if (typeof x !== 'number') {
var x = 0;
} else {
x++;
}
return x
}
I don't want any globals or vars outside of the function hopefully.
What I've got always returns 0;
A closure can do that:
var uniqueNum = (function(){
var num = 0;
return function(){
return num++;
}
}());
uniqueNum(); // 0
uniqueNum(); // 1
A "static" variable works too, as suggested in other answers.
You can implement a "static" variable like this:
function uniqueNum() {
return uniqueNum.counter = (uniqueNum.counter || 0)+1;
}
The following will use the function itself for storing the counter:
function uniqueNum() {
if (uniqueNum.x == null) {
uniqueNum.x = 0;
} else {
uniqueNum.x++;
}
return uniqueNum.x;
}
console.log(uniqueNum()); // 0
console.log(uniqueNum()); // 1
console.log(uniqueNum.x); // 1

Categories

Resources