How to store previous result into a var - javascript

Pretty new to Javascript..
I have managed to script this simple code here:
var currentstock = 50;
function stockminus(x){
newcurrent = currentstock - x;
return newcurrent;
};
console.log(stockminus(10));
the output of this must be : 40
How can I store that new output into currentstock as the new value or in other words overwrite that var?
so next time I call that function again, output should be : 30
Becasue the new currentstock is 40 from the previous call

Simple, currentstock = stockminus(10)

The let statement declares a block scope local variable, optionally initializing it to a value.
So, every time you are working in the same scope you can do:
let currentstock = 50;
function stockminus(x) {
return currentstock -= x;
};
console.log(stockminus(10));
console.log(stockminus(10));

var stockDetails = (function(initialValue){
var currentStock = initialValue;
return {
getCurrentStock: function() {
return currentStock;
},
stockminus: function(x) {
//add additional logic to check negative cases
currentStock-= x;
return currentStock;
}
}
})(50);
you can use this type of modular patterns to access data using methods and later extend it as per needs.
access it like
stockDetails.getCurrentStock();
stockDetails.stockminus(10);

Related

Passing values from an object inside a function

I have been working all day trying to pass the value of "returnData.salary" inside the "readData" function to
the object inside the "calculateTax" function which is suppose to take the salary value and calculate state and federal taxes. I am stumped, I can't find anything on the internet which provides a good example for me to work with. The examples are either way to simple or super complex. Any help would be appreciated.
I apologize in advance if I did not submit this question in the correct format. This is my first time asking for help on stackoverflow.
function readForm() {
var returnData = {};
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
$("#name2").text(returnData.name);
$("#lastName2").text(returnData.lastName);
$("#age2").text(returnData.age);
$("#gender2").text(returnData.gender);
$("#salary2").text(returnData.salary);
$("#myTextArea2").text(returnData.myTextArea);
if ($(isManager).is(':checked')) {
$("#isManager2").text("Yes");
}
else {
$("#isManager2").text("No");
}
//$("#employeeForm")[0].reset();
} //end of readForm function
function calculateTax() {
console.log("Button Works");
var calculateTax = {
state: function(num) {
num *= 0.09;
return num;
}
, federal: function(num) {
if (num > 10000) {
num *= 0.2;
return num;
}
else {
num * 0.1;
return num;
}
}
, exempt: true
};
}
//Invoke readForm function when the submit button is clicked.
$(document).ready(function () {
$("#btnSubmit").on("click", readForm);
$("#btnCalculate").on("click", calculateTax);
})
</script>
Well, simply put; you can't. Not like this anyway. Or, at least not pass the value to the function directly.
You are using global functions right now, which are not inside a class. If it was inside a class, you could instantiate the class and save it to this (which would be the class' instance). However, I'm assuming classes are a bit over complicated in this case. What you could do, is set variables globally so all functions can use them, like this;
//declare the global variable so it exists for every function
var returnData = {};
function readForm() {
//We do NOT redeclare the "var" again. It's global now.
returnData = {}; //Reset the global variable when this function is called
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
//Rest of your function
}
function calculateTax(){
console.log(returnData) //works here
}
Note that you do overwrite global variables, so it's best to reset them on every function call. You might get old data stuck in there, otherwise.

Losing scope on recursive call

I'm creating a module that accepts a data set and an integer n and recursively fills that dataset with n products at a time, after the first call, the function loses its scope and errors out. Why, And what's the best practice for fixing this?
Code:
function ProductFactory(){
var bigArr = [0,1,2,3,4,5,6,7,8,9];
var smallArr = [1,2,3,4];
return {
getProductList: getProductList,
getAllProducts: getAllProducts
};
function getProductList(start, size){ return start < 5 ? bigArr : smallArr }
function getAllProducts(batchSizeRequested, dataSet) {
var startPage = dataSet.length / batchSizeRequested;
var productBatch = this.getProductList(startPage, batchSizeRequested);
dataSet = dataSet.concat(productBatch);
if (productBatch.length === batchSizeRequested)
getAllProducts(batchSizeRequested, dataSet);
}
}
var productGetter = new ProductFactory();
productGetter.getAllProducts(10, []);
1) First of all you shouldn't call getProductList using this, in this case you can just call it as it is, because getProductList is not a function that was assigned directly to this object. It is just a closure that uses local variables in it's code. If you want to call function using this, you should assign it using this, for example this.getProductList = function() {}
2) I don't think there are other scoping problems except redundant this, but I found another issue, though.
You are not actually return anything from your function, plus recursive call does not have an exit point.
Fixed code looks like this.
function ProductFactory(){
var bigArr = [0,1,2,3,4,5,6,7,8,9];
var smallArr = [1,2,3,4];
return {
getProductList: getProductList,
getAllProducts: getAllProducts
};
function getProductList(start, size){ return start < 5 ? bigArr : smallArr }
function getAllProducts(batchSizeRequested, dataSet) {
var startPage = dataSet.length / batchSizeRequested;
var productBatch = getProductList(startPage, batchSizeRequested);
dataSet = dataSet.concat(productBatch);
if (productBatch.length === batchSizeRequested) {
return getAllProducts(batchSizeRequested, dataSet);
} else {
return dataSet;
}
}
}
var productGetter = ProductFactory();
var products = productGetter.getAllProducts(10, []);
console.log(products)
The typical approach to a function call like this is to assign an external value to this (typically called self):
function ProductFactory(){
...
var self = this;
function getAllProducts(batchSizeRequested, dataSet) {
...
getAllProducts.apply(self, [batchSizeRequested, dataSet]);
}
}
In this case, however, please try to remember that you have defined a closure function getAllProducts that is only privately accessible internal to the constructor. Instead you should probably do:
function ProductFactory(){
...
var self = this;
this.getAllProducts = function(batchSizeRequested, dataSet) {
...
self.getAllProducts(batchSizeRequested, dataSet);
}
}

Private variables with requirejs and closure

I am trying to make a class with private variables in requirejs. ( means I don't want anyone to access this variable and only private method can be used.)
numbox.js
define(function(){
var counter=0;
function Numbox(){
}
Numbox.prototype = {
add_and_show:function(){
counter++; alert(counter);
}
}
return Numbox;
}
This is not correct if I create any new instance of Numbox and call the method, all instances will share the same counter as follows.
require(['numbox.js'], function(Numbox){
var box1 = new Numbox();
var box2 = new Numbox();
box1.add_and_show(); // alert(1);
box2.add_and_show(); // alert(2); instead of "1"
}
And even though I put counter under constructer function as follows, It can work but it does not realize my goal as I want it to be private. (I can still access "counter" by box1.counter or box2.counter)
numbox.js
define(function(){
function Numbox(){
this.counter =0;
}
Numbox.prototype = {
add_and_show:function(){
this.counter++; alert(this.counter);
}
}
return Numbox;
}
Please suggest the correct way to do this. Thx!
You can't have everything. (As the sage says, "Where would you put it?" :-/ )
In this case, what you really can't have is entirely encapsulated data that prototype functions have access to. As elclanrs says, you're second example is fine if you're willing to forgo the privacy. On the other hand, if the privacy is more important than memory, you can do this instead:
define(function(){
function Numbox(){
var counter = 0;
this.add_and_show=function(){
counter++; alert(counter);
}
}
return Numbox;
}
Now counter is entirely private. But each Numbox instance has its own private copy of add_and_show. You can make your own decision about the tradeoff. But I've never seen any technique which allows you to achieve both.
If you really need this (tip, you probably don't), a way to do it is to keep track of instances and counters in the "private" scope, like so:
define(function(){
var counters = [];
var instances = [];
function Numbox() {
instances.push(this);
counters.push(0);
}
Numbox.prototype = {
addAndShow: function() {
var idx = instances.indexOf(this);
var counter = counters[idx]++;
return counter;
}
};
return Numbox;
});
var n = new Numbox();
console.log(n.addAndShow()); //=> 0
console.log(n.addAndShow()); //=> 1
console.log(n.addAndShow()); //=> 2
var n2 = new Numbox();
console.log(n2.addAndShow()); //=> 0
console.log(n2.addAndShow()); //=> 1
// More tests
console.log(n.addAndShow()); //=> 3
console.log(n2.addAndShow()); //=> 2

Javascript array is undefined... and I'm not sure why

I'm trying to translate a PHP class into JavaScript. The only thing I'm having trouble with is getting an item out of an array variable. I've created a simple jsfiddle here. I cannot figure out why it won't work.
(EDIT: I updated this code to better reflect what I'm doing. Sorry for the previous mistake.)
function tattooEightBall() {
this.subjects = ['a bear', 'a tiger', 'a sailor'];
this.prediction = make_prediction();
var that = this;
function array_random_pick(somearray) {
//return array[array_rand(array)];
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*somearray.length)];
return random;
}
function make_prediction() {
var prediction = array_random_pick(this.subjects);
return prediction;
}
}
var test = tattooEightBall();
document.write(test.prediction);
​
Works fine here, you are simple not calling
classname();
After you define the function.
Update
When you make a call to *make_prediction* , this will not be in scope. You are right on the money creating a that variable, use it on *make_prediction* :
var that = this;
this.prediction = make_prediction();
function make_prediction() {
var prediction = ''; //initialize it
prediction = prediction + array_random_pick(that.subjects);
return prediction;
}
You can see a working version here: http://jsfiddle.net/zKcpC/
This is actually pretty complex and I believe someone with more experience in Javascript may be able to clarify the situation.
Edit2: Douglas Crockfords explains it with these words:
By convention, we make a private that variable. This is used to make
the object available to the private methods. This is a workaround for
an error in the ECMAScript Language Specification which causes this to
be set incorrectly for inner functions.
To see the complete article head to: http://javascript.crockford.com/private.html
You never call classname. Seems to be working fine.
Works for me:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
}());
Were you actually calling the classname function? Note I wrapped your code block in:
([your_code]());
I'm not sure what you're trying to accomplish exactly with the class structure you were using so I made some guesses, but this code works by creating a classname object that has instance data and a pickone method:
function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
this.pickone = function() {
var length = this.list.length;
var random = this.list[Math.floor(Math.random()*length)];
return random;
}
}
var cls = new classname();
var random = cls.pickone();
You can play with it interactively here: http://jsfiddle.net/jfriend00/ReL2h/.
It's working fine for me: http://jsfiddle.net/YznSE/6/ You just didn't call classname(). If you don't call it, nothing will happen ;)
Make it into a self-executing function like this:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length; //<---WHY ISN'T THIS DEFINED??
var random = somearray[Math.floor(Math.random() * length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
})();
var test = tattooEightBall();
document.write(test.prediction);
Should be:
var test = new tattooEightBall(); //forgot new keyword to create object
document.write(test.prediction()); // forgot parens to fire method
and:
this.prediction = make_prediction();
Should be:
this.prediction = make_prediction;

Use variable's value as variable in javascript

I have a variable with a value, let's say
var myVarMAX = 5;
In HTML I have an element with id="myVar".
I combine the id with the string MAX (creating a string myVarMAX). My question is how can I use this string to access a variable with the same name?
You COULD use eval, but if you have the var in the window scope, this is better
var myVarMAX = 5;
var id="MAX"; // likely not in a var
alert(window["myVar"+id]); // alerts 5
However Don't pollute the global scope!
A better solution is something like what is suggested in the link I posted
var myVars = {
"myVarMin":1,
"myVarMax":5,
"otherVarXX":"fred"
} // notice no comma after the last var
then you have
alert(myVars["myVar"+id]);
Since this post is referred to often, I would like to add a use case.
It is probably often a PHP programmer who gives Javascript/Nodejs a try, who runs into this problem.
// my variables in PHP
$dogs = [...]; //dog values
$cats = [...]; //cat values
$sheep = [...]; //sheep values
Let's say I want to save them each in their own file (dogs.json, cats.json, sheep.json), not all at the same time, without creating functions like savedogs, savecats, savesheep. An example command would be save('dogs')
In PHP it works like this:
function save($animal) {
if(!$animal) return false;
file_put_contents($animal.'.json', json_encode($$animal));
return true;
}
In Nodejs/Javascript it could be done like this
// my variables in NodeJS/Javascript
let dogs = [...]; //dog values
let cats = [...]; //cat values
let sheep = [...]; //sheep values
function save(animal) {
if (!animal) return false;
let animalType = {};
animalType.dogs = dogs;
animalType.cats = cats;
animalType.sheep = sheep;
fs.writeFile(animal + '.json', JSON.stringify(animalType[animal]), function (err){
if (err) return false;
});
return true;
}

Categories