add the calculation function to the calculator js - javascript

How to add a calculation function to the loan calculator. When I add
another block (else) function does not work and other functions too. How do I add a function correctly? That the data below could work correctly.
// global variables
var min, max, creditBody, oneTimeCommission, monthlyCommission, rate, grace, smsCost, monthlyFee;
// calculating function
function calc(type, summ, term) {
min = 3, max = 36;
if (type == "standart") {
$("#month-slider").slider('option', {min: 3});
$("#min").text('3');
oneTimeCommission = 0.0199;
monthlyCommission = 0.0199;
rate = 0.0001;
smsCost = 20;
creditBody = summ / (1 - monthlyCommission);
monthlyFee = ((creditBody + (creditBody * term * monthlyCommission)) / term) + smsCost;
}
else {
min = 4, max = 36;
$("#month-slider").slider('option',{min: min});
$("#min").text('4');
if (term < min) {
term = min;
}
oneTimeCommission = 0;
monthlyCommission = 0.035;
grace = 4;
smsCost = 20;
creditBody = summ / (1 - 0);
monthlyFee = ((creditBody + (creditBody * (term - grace) * monthlyCommission)) / term) + smsCost;
}
// my add block - not work :(
else {
min = 8, max = 36;
$("#month-slider").slider('option',{min: min});
$("#min").text('8');
if (term < min) {
term = min;
}
oneTimeCommission = 0;
monthlyCommission = 0.035;
grace = 8;
smsCost = 20;
creditBody = summ / (1 - 0);
monthlyFee = ((creditBody + (creditBody * (term - grace) * monthlyCommission)) / term) + smsCost;
}
//
var result = {type:type,summ:summ,term:term};
$("#monthlyFee").text(parseInt(monthlyFee) + " грн");
$("#total-sum").text(parseInt($("#product-sum").val()) + " грн");
$("#total-month").text(parseInt($("#credit-month").val()) + " мic");
return result
}

Maybe this can be a better way to handle your case, avoiding if/else conditions and make it more pure.
calc = ( type, params ) => {
const typesFn = {
'standart': () => {
// do something here
},
'test': ( params ) => {
console.log( params );
}
}
typesFn[type](params); // call && exec
}
calc( 'test', {summ: null, term:null, test: true});
I hope that helps you :)

Related

does this web worker execute parallely?

Hi I am learning web worker and I believe that I have managed to make it work but still, I am struggling to figure out how to make it parallel.
for (let m = 0; m < keyCountMap.length; m += 2) {
fetchWorker.postMessage([keyCountMap[m], keyCountMap[m + 1]]);
}
I have this for loop inside which there was another for loop and i transferred all the code into the fetchWorker.
import Worker from "./worker/fetcher.worker.js";
const fetchWorker = new Worker();
I want to parallelize this at least with 5/10 thread so can i just add fetchWorker.postMessage with different parameter one after another inside the loop and increment the variable "m" of likewise
for (let m = 0; m < keyCountMap.length; m += 2) {
fetchWorker.postMessage([keyCountMap[m], keyCountMap[m + 1]]);
fetchWorker.postMessage([keyCountMap[m+2], keyCountMap[m + 3]]);
}
Does this act as two threads per loop?
This is my fetcher code:
import { Copc, Key } from "copc";
import * as THREE from "three";
const color = new THREE.Color();
const colors = [];
var nodePages, pages, receivedData, copc;
let x_min, y_min, z_min, x_max, y_max, z_max, width;
let positions = [];
let filename = "https://s3.amazonaws.com/data.entwine.io/millsite.copc.laz";
const readPoints = (id, getters) => {
let returnPoint = getXyzi(id, getters);
positions.push(
returnPoint[0] - x_min - 0.5 * width,
returnPoint[1] - y_min - 0.5 * width,
returnPoint[2] - z_min - 0.5 * width
);
const vx = (returnPoint[3] / 65535) * 255;
color.setRGB(vx, vx, vx);
colors.push(color.r, color.g, color.b);
};
function getXyzi(index, getters) {
return getters.map((get) => get(index));
}
async function load() {
copc = await Copc.create(filename);
let scale = copc.header.scale[0];
[x_min, y_min, z_min, x_max, y_max, z_max] = copc.info.cube;
width = Math.abs(x_max - x_min);
receivedData = await Copc.loadHierarchyPage(
filename,
copc.info.rootHierarchyPage
);
nodePages = receivedData.nodes;
pages = receivedData.pages;
postMessage(200);
}
async function loadData(myRoot, pointCount) {
const view = await Copc.loadPointDataView(filename, copc, myRoot);
let getters = ["X", "Y", "Z", "Intensity"].map(view.getter);
for (let j = 0; j < pointCount; j += 1) {
readPoints(j, getters);
}
postMessage([positions, colors]);
}
load();
onmessage = function (message) {
let mapIndex = message.data[0];
let pointCount = message.data[1];
console.log(mapIndex);
let myRoot = nodePages[mapIndex];
loadData(myRoot, pointCount);
};
Can anyone help me please !!

How to add "IF result = X" than "RETURN x" to this javascript code?

My Code:
const crypto = require('crypto');
const crashHash = '';
// Hash from bitcoin block #610546. Public seed event: https://twitter.com/Roobet/status/1211800855223123968
const salt = '0000000000000000000fa3b65e43e4240d71762a5bf397d5304b2596d116859c';
function saltHash(hash) {
return crypto
.createHmac('sha256', hash)
.update(salt)
.digest('hex');
}
function generateHash(seed) {
return crypto
.createHash('sha256')
.update(seed)
.digest('hex');
}
function divisible(hash, mod) {
// We will read in 4 hex at a time, but the first chunk might be a bit smaller
// So ABCDEFGHIJ should be chunked like AB CDEF GHIJ
var val = 0;
var o = hash.length % 4;
for (var i = o > 0 ? o - 4 : 0; i < hash.length; i += 4) {
val = ((val << 16) + parseInt(hash.substring(i, i + 4), 16)) % mod;
}
return val === 0;
}
function crashPointFromHash(serverSeed) {
const hash = crypto
.createHmac('sha256', serverSeed)
.update(salt)
.digest('hex');
const hs = parseInt(100 / 4);
if (divisible(hash, hs)) {
return 1;
}
const h = parseInt(hash.slice(0, 52 / 4), 16);
const e = Math.pow(2, 52);
return Math.floor((100 * e - h) / (e - h)) / 100.0;
}
function getPreviousGames() {
const previousGames = [];
let gameHash = generateHash(crashHash);
for (let i = 0; i < 100; i++) {
const gameResult = crashPointFromHash(gameHash);
previousGames.push({ gameHash, gameResult });
gameHash = generateHash(gameHash);
}
return previousGames;
}
function verifyCrash() {
const gameResult = crashPointFromHash(crashHash);
const previousHundredGames = getPreviousGames();
return { gameResult, previousHundredGames };
}
console.log(verifyCrash());
Code Sandbox
I'm trying to make this code show the results it already shows, but I want it to add something to the end of each gameResult data so it would look like this: gameResult: 4.39 "maybe"
I've tried to add something like this to the code with no luck. I had it working to the point where it would only return the very first gameResult but not the ones after. If someone could help that would be great, or if you have another way other than this code below that I was trying to use, that works too.
function gameResult
const result =
if (gameResult === 1) {
return "no";
};
if (gameResult <= 3) {
return "maybe";
};
if (gameResult <= 10) {
return "yes";
};
So, if I understand correctly the expected output should be like this,
{
"gameResult": "4.39 "yes"",
"previousHundredGames": [...]
}
I am able to do this by modifying the verifyCrash function to this,
function verifyCrash() {
let gameResult = crashPointFromHash(crashHash);
const previousHundredGames = getPreviousGames();
if (gameResult === 1) {
gameResult=+' "no"';
}
if (gameResult <= 3) {
gameResult=+' "maybe"';
}
if (gameResult <= 10) {
gameResult+= ' "yes"';
}
return { gameResult, previousHundredGames };
}
Check this link to see it in action,
https://codesandbox.io/s/crash-forked-f7fb7

Node require 3rd party script

I need to get my google one-time password every time when I receive a new one.
Please check here also.
I want to use this code inside my app.js (in server side java script file). I have been trying to figure it out but could't make it.
I copied and pasted to all code in that website and created at under same directory and required it.
I tried this:
myKey = '**my_key_is_here';
require('./sha.js');
function dec2hex(s) { return (s < 15.5 ? '0' : '') + Math.round(s).toString(16); }
function hex2dec(s) { return parseInt(s, 16); }
function base32tohex(base32) {
var base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
var bits = "";
var hex = "";
for (var i = 0; i < base32.length; i++) {
var val = base32chars.indexOf(base32.charAt(i).toUpperCase());
bits += leftpad(val.toString(2), 5, '0');
}
for (var i = 0; i + 4 <= bits.length; i += 4) {
var chunk = bits.substr(i, 4);
hex = hex + parseInt(chunk, 2).toString(16);
}
return hex;
}
function leftpad(str, len, pad) {
if (len + 1 >= str.length) {
str = Array(len + 1 - str.length).join(pad) + str;
}
return str;
}
function updateOtp() {
var key = base32tohex(myKey);
var epoch = Math.round(new Date().getTime() / 1000.0);
var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0');
// updated for jsSHA v2.0.0 - http://caligatio.github.io/jsSHA/
var shaObj = new jsSHA("SHA-1", "HEX");
shaObj.setHMACKey(key, "HEX");
shaObj.update(time);
var hmac = shaObj.getHMAC("HEX");
if (hmac == 'KEY MUST BE IN BYTE INCREMENTS') {
console.log('something wrong with HMAC');
} else {
var offset = hex2dec(hmac.substring(hmac.length - 1));
var part1 = hmac.substr(0, offset * 2);
var part2 = hmac.substr(offset * 2, 8);
var part3 = hmac.substr(offset * 2 + 8, hmac.length - offset);
}
var otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) + '';
otp = (otp).substr(otp.length - 6, 6);
var test = otp;
console.log(test);
}
function timer() {
var epoch = Math.round(new Date().getTime() / 1000.0);
var countDown = 30 - (epoch % 30);
if (epoch % 30 == 0) updateOtp();
// $('#updatingIn').text(countDown);
}
function startFactor() {
updateOtp();
setInterval(timer, 1000);
};
startFactor();
but getting this output :
ReferenceError: jsSHA is not defined
Basic Question is: How can I use this file in my Nodejs project.
Install it from npm repo:
npm install jssha --save or npm install jssha --save-dev
and then require:
jsSHA = require("jssha");
It was so simple to do with speakeasy !
That was what I needed.
Solved.

Generate "Unique" 5 digits ID with javascript (99999 combinations) in random order

I want to generate an Unique 5 digits ID + 784 at the begining, the constraint, I can execute the script only one time, and I have to avoid the first 100 numbers so It can't be 00100 and lower. Since I use timestamp and I can execute only my script one time how I can handle this ?
I did this it's maybe dumb but at least I tried.
ConcatedID();
function ConcatedID()
{
var uniqID = checkProtectedRange();
if (checkProtectedRange())
{
var BarcodeID = 784 + uniqID;
return BarcodeID;
}
else
checkProtectedRange();
}
function checkProtectedRange()
{
var uniqueID = GenerateUniqueID();
var checkRange = uniqueID.substr(uniqueID.length - 3);
var checkRangeINT = parseInt(checkRange);
if (checkRangeINT <= 100)
return (false);
else
return (true);
}
function GenerateUniqueID()
{
var lengthID = 5;
var timestamp = + new Date();
var ts = timestamp.toString();
var parts = ts.split("").reverse();
var id = "";
var min = 0;
var max = parts.length -1;
for (var i = 0; i < lengthID; ++i)
{
var index = Math.floor(Math.random() * (max - min + 1)) + min;
id += parts[index];
}
gs.log('Generate ID ' + id);
return id;
}
Without being able to track previously used IDs, you're left with chance to prevent duplicates. Your shenanigans with Date doesn't really change that. See the birthday problem.
Given that, just follow the most straight-forward method: Generate a random string consisting of five digits.
function GenerateUniqueID() {
return ('0000'+(Math.random() * (100000 - 101) + 101)|0).slice(-5);
}
Or, if you want just the final integer with constraints applied:
function GenerateUniqueID() {
return (Math.random() * (78500000 - 78400101) + 78400101)|0;
}

I have created a webpage that will factorialize a number. I have created that function. Now I need to create a function that will show my math.

Can anyone help me to do this? The function is empty below and I am unsure how to proceed. I have the factorized number showing on the webpage now I would like the math to show before it. Something like this;
A user inputs: 3
Our site outputs: "1 x 2 x 3 = 6"
function factorialize(num) {
var total = 1;
if (num > 1) {
for (var i = 1; i <= num; i += 1) {
total *= i;
}
}
return total;
}
function showMath() {
};
$(document).ready(function() {
$("form#new-item").submit(function(event) {
event.preventDefault();
var userInput = parseInt($("input#input1").val());
var result = factorialize(userInput);
var myWork = showMath(userInput);
// var
$("#output").text(myWork + " = " + result);
});
});
You should build up an array of all the factors. Then it is easy to reduce() the array to a single value or join() it into a string.
function toFactorialArray(num){
var n = num,
arr = [n];
while (--n) arr.push(n);
return arr;
}
function getResult(arr){
return arr.reduce(
function( memo, current ) {
return memo * current
}, 1
);
}
function getWork(arr){
return arr.reverse().join(' * ');
}
$(document).ready(function() {
$("form#new-item").submit(function(event) {
event.preventDefault();
var userInput = parseInt($("input#input1").val());
var factors = toFactorialArray(userInput);
var result = getResult(factors);
var myWork = getWork(factors);
$("#output").text(myWork + " = " + result);
});
});

Categories