function writing function in JS - javascript

I have functions in JS that must be hard-coded for some reason. How do I make a function that writes this hard-coded function? Here's my example; assuming obj is a multi-array/JSON object:
function foo2(obj) {
var t = obj["key1"];
t = t["key2"];
return t;
}
function fooN(obj) {
var t = obj["key1"];
t = t["key2"];
...//more goes here
t = t["keyN"];
return t;
}
I know there're easier ways to access multi-array/object, but hard-coded functions like this is by far the fastest, since there is no variable substitution. Thank you.

I don't advocate it, but here's how you could do it:
function defineAccessor(propArray) {
var accessors = propArray.join('.');
return new Function('obj', 'return obj.' + accessors);
}
var x = { key1: { key2: 3 } };
var foo2 = defineAccessor(['key1', 'key2']);
alert(foo2(x)); // alerts 3

Seems like some strange requirements, but a possible solution is to add the functions to window using window['foo' + number].
The main tricky bit in this solution is the closure in the middle that ensures that the correct value of i is used. This is done by calling a function that takes i as an arg and returns a function.
var N = 5;
fooX = function(obj, x) {
var t = obj["key" + 1];
for (var i = 2; i <= x; i++) {
t = t["key" + i];
}
return t;
}
for (var i = 1; i <= N; i++) {
window['foo' + i] = (function(x) {
return function(obj) {
return fooX(obj, x);
}
})(i);
}
var obj = {
key1: {
key2: {
key3: {
key4: {
key5: 5
}
}
}
}
}
var message = "Results:<br>" +
"foo1(obj) = " + foo1(obj) + "<br>" +
"foo2(obj) = " + foo2(obj) + "<br>" +
"foo3(obj) = " + foo3(obj) + "<br>" +
"foo4(obj) = " + foo4(obj) + "<br>" +
"foo5(obj) = " + foo5(obj);
document.body.innerHTML = message;

Related

Pass a function reference to a nested closure

In the code below I would like to pass a reference to a function that resides on the parent scope to the nested scope of the function "nested", so I can call the function on the parent scope from the nested function. I tried passing it in as a parameter but it doesn't work. I'm just learning/messing around with nested closures and wondering if this could be done.
I would like to have the syntax for calling nested be: callme.nested()
var obj = function(val){
var access = val;
var apex = 0;
return {
callme : (function(siblyng){
var privatevar = 2;
return {
nested : function(){
privatevar++;
apex = privatevar;
return access + " " + privatevar + " " + siblyng("child");
}
}
})(this.sibling),
assess : function(){
return apex + " " + this.sibling("parent");
},
sibling : function(val){
return "returned from " + val + " scope";
}
}
}
var objref = obj(true);
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.assess());
console.log(objref.sibling('global'));
If I understood you well, you can do it like so
var obj = function(val){
var access = val;
var apex = 0;
var ret;
return (ret = {
callme : function() {
var privatevar = 2;
return {
nested : function(){
privatevar++;
apex = privatevar;
return access + " " + privatevar + " " + ret.sibling("child");
}
};
}(),
assess : function(){
return apex + " " + this.sibling("parent");
},
sibling : function(val){
return "returned from " + val + " scope";
}
});
};
var objref = obj(true);
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.callme.nested());
console.log(objref.assess());
console.log(objref.sibling('global'));
Your this in the following code was pointing to the global Window object and so it was not able to find the method. You could have directly called this.sibling in your nested method without the need of passing it.
callme : (function(siblyng){
var privatevar = 2;
return {
nested : function(){
privatevar++;
apex = privatevar;
return access + " " + privatevar + " " + siblyng("child");
}
}
})(this.sibling),

access an object in a function using javascript

I am new to JS and have created this original problem from CodeAcademy which works. Now I wanted to put my flock of sheep into an object and access it using my sheepCounter function. I am new to accessing key/values from an object and am stuck on what I am doing wrong. Thanks in advance!
Original Code
var sheepCounter = function (numSheep, monthNumber, monthsToPrint) {
for (monthNumber = monthNumber; monthNumber <= monthsToPrint; monthNumber++) {
numSheep *= 4;
console.log("There will be " + numSheep + " sheep after " + monthNumber + " month(s)!");
}
return numSheep;
}
New Code:
var flock = {
sheep: 4,
month: 1,
totalMonths: 12
};
var sheepCounter = function (counter) {
for (counter[month] = counter[month]; counter[month] <= counter[totalMonths]; counter[month]++) {
numSheep *= 4;
console.log("There will be " + counter[sheep] + " sheep after " + counter[month] + " month(s)!");
}
return counter[sheep];
}
Found the error in your solution:
var sheepCounter = function (counter) {
for (counter['month'] = counter['month']; counter['month'] <= counter['totalMonths']; counter['month']++) {
counter['sheep'] *= 4;
console.log("There will be " + counter['sheep'] + " sheep after " + counter['month'] + " month(s)!");
}
return counter['sheep'];
}
You can access your Flock Object like so,
alert(flock.sheep); //4
If you have an array in an object, like
names: ['joe','tom','bob'];
You would access that like so,
alert(flock.names[0]); // joe
alert(flock.names[2]); // bob

Function Scope issue when declaring an array of objects

This is the code that I currently have, one problem that is happening is I cannot use test() because presets[index].name and value are not visible outside of their function scope, how should I declare my array of objects in the global scope in order for me to be able to access these two variables in other functions?
var presets = [];
var index;
function CreatePresetArray(AMib, AVar) {
var parentpresetStringOID = snmp.getOID(AMib, AVar);
var presetStringOID = parentpresetStringOID;
parentpresetStringOID = parentpresetStringOID.substring(0, parentpresetStringOID.length - 2);
log.error("parentpresetStringOID is " + parentpresetStringOID);
var presetswitches = {};
for (var i = 1; i < 41; i++) {
presets.push(presetswitches);
try {
log.error("presetStringOID before getNextVB= " + presetStringOID);
vb = snmp.getNextVB(presetStringOID);
presetStringOID = vb.oid;
log.error("presetStringOID after getnextVB= " + presetStringOID);
var presetStringVal = snmp.get(presetStringOID);
log.error("presetStringVal= " + presetStringVal);
index = i - 1;
presets[index].name = presetStringOID;
presets[index].value = presetStringVal;
log.error("preset array's OID at position [" + index + "] is" + presets[index].name + " and the value stored is " + presets[index].value);
//log.error("presets Array value ["+index+"] = "+presets[index].configs);
if (presetStringOID.indexOf(parentpresetStringOID) != 0) {
break;
}
} catch (ie) {
log.error("couldn't load preset array " + index);
};
};
}
CreatePresetArray(presetMib, "presetString");
function test() {
for (i = 1; i < 41; i++) {
log.error("test" + presets[index].name + " " + presets[index].value);
};
}
test();
The for loop in your function test iterates over i but uses index inside the loop. Perhaps you meant to use
for (i = 0; i < 40; i++) { // 1 lower as you were using `index = i - 1` before
log.error("test" + presets[i].name + " " + presets[i].value);
}
Re-wrote your code. I don't think I made that much by way of change. If this doesn't clear up your problem, consider: Is the catch happening each iteration? Is the problem actually coming from a different method which is only visible here? Also, consider logging the whole presets Array when debugging to see what it looks like.
var presets = [];
function CreatePresetArray(AMib, AVar) {
var parentPresetOID, presetOID, presetValue, preset, vb, i;
parentPresetOID = snmp.getOID(AMib, AVar);
presetOID = parentPresetOID; // initial
parentPresetOID = parentPresetOID.substring(0, parentPresetOID.length - 2);
log.error("parentPresetOID is " + parentPresetOID);
presets = []; // empty array in case not already empty
for (i = 0; i < 40; ++i) {
try {
preset = {}; // new object
// new presetOID
vb = snmp.getNextVB(presetOID);
presetOID = vb.oid;
log.error("presetOID after getnextVB= " + presetOID);
// new value
presetValue = snmp.get(presetOID);
log.error("presetValue= " + presetValue);
// append data to object
preset.name = presetOID;
preset.value = presetValue;
// append object to array
presets.push(preset);
// more logging
log.error(
"preset array's OID at position [" + i + "]" +
" is" + presets[i].name + " and " +
"the value stored is " + presets[i].value
);
if (presetOID.indexOf(parentPresetOID) !== 0) {
break;
}
} catch (ie) {
log.error("couldn't load preset array " + i);
if (presets.length !== i + 1) { // enter dummy for failed item
presets.push(null);
}
}
}
}
Two options come to mind immediately:
you could pass the preset array as a argument to test().
You could put both CreatePresetArray() and test() inside a wrapper function and declare preset array at the top of your wrapper. That would give them both access to the variable.
It's generally considered Bad Form to declare globals if it can be avoided. Pollutes the namespace.

Dynamically change prototype for JavaScript object

My final task is to fully recover object previously saved using JSON. For now JSON only allows to recover data, but not behaviour. A possilbe solution is to create a new object (lets call it obj) and copy data from JSON-recovered-object to obj. But it doesn't look nice for me. What I am asking, is there a way to dynamically change object prototype in JavaScript?
It's how I solve problem at the moment (using self-made copy method):
(this code on JSFiddle)
function Obj() {
this.D = "D";
this.E = "E";
this.F = "F";
this.toString = function () {
return this.D + " * " + this.E + " * " + this.F;
};
this.copy = function (anotherObj) {
for (var property in anotherObj) {
if (isDef(anotherObj[property]) && isDef(this[property])) {
this[property] = anotherObj[property];
}
}
}
}
;
$(document).ready(function () {
var str = $.toJSON(new Obj());
$("#result").append("<p>JSON: " + str + "</p>");
var obj = new Obj();
obj.copy($.parseJSON(str));
$("#result").append("<p>Recovered obj: " + obj.toString() + "</p>");
});
function isDef(variable)
{
return typeof variable !== undefined;
}
There are easier methods provided by many popular JS libraries.
For example, if you are using jQuery, you might use the jQuery.extend() method instead of your copy function like so:
var obj = $.extend(new Obj(), $.parseJSON(str));
Forked jsFiddle here.
EDIT: Based on ideas from this question, I was able to get the restored object to have all the nested functionality as well, see the updated jsFiddle.
The core idea is to use prototypes instead of properties, and then make sure the object restored from JSON (which is just data) is the first parameter to $.extend():
function Obj2() {
this.A = "A";
}
Obj2.prototype.toString = function() {
return this.A;
};
function Obj() {
this.A = new Obj2();
this.D = "D";
this.E = "E";
this.F = "F";
}
Obj.prototype.toString = function() {
return this.A.toString() + " * " + this.D + " * " + this.E + " * " + this.F;
};
var str = $.toJSON(new Obj());
$("#result").append("<p>JSON: " + str + "</p>");
var obj = jQuery.extend($.parseJSON(str), new Obj());
$("#result").append("<p>Recovered obj: " + obj.toString() + "</p>");

Javascript 'undefined' when using a function variable on an array of objects

I have the following (example) array of objects:
var theArray = [
{theId:'1', num: 34},
{theId:'2', num: 23},
{theId:'5', num: 26}
];
and this function, which works fine to loop through them:
function printValues() {
var i = 0;
for(i; i<theArray.length; i++) {
var obj = theArray[i];
document.getElementById('result1').innerHTML += obj.theId + ' = ' + obj.num + '<br>';
}
}
However, if I want to abstract this function for use on similar arrays by using function variables to access objects within them, like this:
function printValuesVar(arr,elemId,arrId,arrNum) {
var i = 0;
for(i; i<arr.length; i++) {
var obj = arr[i];
document.getElementById(elemId).innerHTML += obj.arrId + ' = ' + obj.arrNum + '<br>';
}
}
'undefined' is the result when called as below (as I'd kind of expect since 'arrId' is not an object name):
printValuesVar(theArray,'result2','theId','num');
How can I use the values passed to the function's variables to access values of objects within the array by name?
rewritten following advice against antipatterns:
function printValuesVar(arr,elemId,arrId,arrNum) {
var i = 0;
var content = '';
for(i; i<arr.length; i+=1) {
var obj = arr[i];
content += obj[arrId] + ' = ' + obj[arrNum] + '<br>';
}
document.getElementById(elemId).innerHTML = content;
}
Try this:
function printValuesVar( arr, elemId, arrId, arrNum ) {
var content = '';
arr.forEach( function ( arrElem ) {
content += arrElem[ arrId ] + ' = ' + arrElem[ arrNum ] + '<br>';
});
document.getElementById( elemId ).innerHTML = content;
}
Or a bit more advanced:
function printValuesVar( arr, elemId, arrId, arrNum ) {
document.getElementById( elemId ).innerHTML = arr.map( function ( arrElem ) {
return arrElem[ arrId ] + ' = ' + arrElem[ arrNum ];
}).join( '<br>' );
}
ES5-shim for shitty browsers
Because you are loking for key "arrId", not the key stored in variable arrId
document.getElementById(elemId).innerHTML += obj[arrId] + ' = ' + obj[arrNum] + '<br>';

Categories

Resources