comparable function to print_r in as3 - actionscript-3

In php we have the method print_r().
Is there anything similar in as3 to print out an object/array?

I found this:
public function analyze(_obj):void {
var item:Object;
switch (typeof(_obj)){
case "object":
write("<object>");
write(_obj.toString());
for each (item in _obj){
analyze(item);
};
write("</object>");
break;
case "xml":
write("<xml>");
write(_obj);
write("</xml>");
break;
default:
write(_obj + " (" + typeof(_obj) + ")");
break;
};
} // analyze()
public function write(_obj):void{
trace(_obj);
} // END write()

Check out [ObjectUtil.toString](http://livedocs.adobe.com/flex/3/langref/mx/utils/ObjectUtil.html#toString()).

Here's another example:
public function rTrace(obj:*, tab:Number=0):void {
if(tab > 10) return;
for(var key:String in obj) {
if(typeof(obj[key]) == "object" || obj[key] is Array) {
tr(doTab(tab)+key+"["+typeof(obj[key])+"]= {");
rTrace(obj[key], tab+2);
tr(doTab(tab)+"}");
} else
tr(doTab(tab)+key+"["+typeof(obj[key])+"]="+obj[key]);
}
}
private function doTab(n:Number):String {
var out:String = "";
for(var i:Number=0; i<n; i++)
out += " ";
return out;
}
private function tr(msg:String):void {
trace(msg);
}
Example usage:
var test:Object = {id:"asdf", count:17,
childs:[1,2,7,39], tasks:{task_1:"test", task_2:true}};
rTrace(test);
Gives the output:
tasks[object]= {
task_2[boolean]=true
task_1[string]=test
}
count[number]=17
childs[object]= {
0[number]=1
1[number]=2
2[number]=7
3[number]=39
}
id[string]=asdf

Related

Flattening JSON but keep original properties

I am trying to flatten properties (i.e. objects, array) of a JSON object, but keep the original properties the same, and turn non-scalar properties into strings.
(I'm doing this because when I use the flat npm package, arrays/objects are flattened, but object keys are surrounded by '' , like in 'task_status.0.data' and do not get stored into AzureTables). If there is a way to fix that and de-string that, it would be an ok solution as well...)
Here's an example you could run on jsfiddle.net
var obj1 = {
"studentId": "abc",
"task_status": [
{
"status":"Current",
"date":516760078
},
{
"status":"Late",
"date":1516414446
}
],
"student_plan": "n"
}
FlattenJson = function(obj){
keys = Object.keys(obj);
var newObj = {};
for(var i=0; i<keys.length; i++){
var theType = typeof(obj[keys[i]]);
console.log(theType);
if(theType === 'array' || theType === 'object'){
console.log(JSON.stringify(obj[keys[i]]));
newObj[keys[i]] = "\"" + JSON.stringify(obj[keys[i]]) + "\"";
}
newObj[keys[i]] = obj[keys[i]];
}
return newObj;
}
var newObj1 = FlattenJson(obj1);
console.log(newObj1, obj1);
However, the newobj1 contains the same original array, instead of a string. How would I fix this?
UPDATED: Thanks to this you have a solution.
var obj1 = {
"studentId": "abc",
"task_status": [
{
"status":"Current",
"date":516760078
},
{
"status":"Late",
"date":1516414446
}
],
"student_plan": "n"
}
function customToString (obj) {
var str = '{';
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
str += prop + ':"' + obj[prop] + '",';
}
}
return str.replace(/.$/,'') + '}';
}
var flattenObject = function(ob) {
var toReturn = {};
for (var i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object') {
var flatObject = flattenObject(ob[i]);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + '.' + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
var newObj1 = flattenObject(obj1);
console.log(newObj1, obj1);
document.write(customToString(newObj1));

Optimise custom function with multiple args to accept ranges

The developers guide of google apps suggests to write your function to accept ranges for optimization like this:
function DOUBLE(input) {
if (input.map) { // Test whether input is an array.
return input.map(DOUBLE); // Recurse over array if so.
} else {
return input * 2;
}
}
I wonder how you would that with multiple arguments?
e.g
function DOUBLEandADD(doubleThis, addThis){
return (doubleThis * 2) + addThis;
}
Do you check both at once and how do you iterate over the ranges?
Something like this perhaps?
function DOUBLEandADD(doubleThis, addThis) {
if (doubleThis.map && addThis.map){
var d = Array.from(doubleThis.values());
var a = Array.from(addThis.values());
for (var i = 0; i < d.length(); i++){
return DOUBLEandADD(d[i],a[i]);
}
} else {
return (doubleThis * 2) + addThis;
}
}
You would wrap the the map function in an anonymous function and pass the additional parameters.
function DOUBLEandADD(input,addend) {
if (input.map) {
return input.map(function(i){return DOUBLEandADD(i,addend)});
} else {
return (input * 2) + addend;
}
}
I wouldn't use map in your case. How about this:
function DOUBLEandADD(doubleThis, addThis) {
if (Array.isArray(doubleThis) || Array.isArray(addThis)) {
if (!Array.isArray(doubleThis) ||
!Array.isArray(addThis) ||
doubleThis.length != addThis.length) {
throw new Error("doubleThis and addThis arrays must be same length.");
}
var results = [];
for (var i = 0; i < doubleThis.length; i++) {
results.push((doubleThis[i] * 2) + addThis[i]);
}
return results;
} else {
return (doubleThis * 2) + addThis;
}
}

Haxe IE9 xmlHTTPrequest issue

I'm having problems displaying my Haxe game in IE9. It's actually not displaying at all. We tracked down the issue inside the compiled JS file for Haxe and found out that the problem is within the haxe.HTTP API.
There are certain things that need to be checked and done for IE9 to work with xmlhttprequests. These things were not done in the Haxe API.
This is the http class without my fix:
this.url = url;
this.headers = new List();
this.params = new List();
this.async = true;
};
$hxClasses["haxe.Http"] = haxe.Http;
haxe.Http.__name__ = ["haxe","Http"];
haxe.Http.prototype = {
setParameter: function(param,value) {
this.params = Lambda.filter(this.params,function(p) {
return p.param != param;
});
this.params.push({ param : param, value : value});
return this;
}
,request: function(post) {
var me = this;
me.responseData = null;
var r = this.req = js.Browser.createXMLHttpRequest();
var onreadystatechange = function(_) {
if(r.readyState != 4) return;
var s;
try {
s = r.status;
} catch( e ) {
s = null;
}
if(s == undefined) s = null;
if(s != null) me.onStatus(s);
if(s != null && s >= 200 && s < 400) {
me.req = null;
me.onData(me.responseData = r.responseText);
} else if(s == null) {
me.req = null;
me.onError("Failed to connect or resolve host");
} else switch(s) {
case 12029:
me.req = null;
me.onError("Failed to connect to host");
break;
case 12007:
me.req = null;
me.onError("Unknown host");
break;
default:
me.req = null;
me.responseData = r.responseText;
me.onError("Http Error #" + r.status);
}
};
if(this.async) r.onreadystatechange = onreadystatechange;
var uri = this.postData;
if(uri != null) post = true; else {
var $it0 = this.params.iterator();
while( $it0.hasNext() ) {
var p = $it0.next();
if(uri == null) uri = ""; else uri += "&";
uri += encodeURIComponent(p.param) + "=" + encodeURIComponent(p.value);
}
}
try {
if(post) r.open("POST",this.url,this.async); else if(uri != null) {
var question = this.url.split("?").length <= 1;
r.open("GET",this.url + (question?"?":"&") + uri,this.async);
uri = null;
} else r.open("GET",this.url,this.async);
} catch( e1 ) {
me.req = null;
this.onError(e1.toString());
return;
}
if(!Lambda.exists(this.headers,function(h) {
return h.header == "Content-Type";
}) && post && this.postData == null) r.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var $it1 = this.headers.iterator();
while( $it1.hasNext() ) {
var h1 = $it1.next();
r.setRequestHeader(h1.header,h1.value);
}
r.send(uri);
if(!this.async) onreadystatechange(null);
}
,onData: function(data) {
}
,onError: function(msg) {
}
,onStatus: function(status) {
}
,__class__: haxe.Http
};
and this is the code WITH the fix:
haxe.Http = function(url) {
this.url = url;
this.headers = new List();
this.params = new List();
this.async = true;
};
$hxClasses["haxe.Http"] = haxe.Http;
haxe.Http.__name__ = ["haxe","Http"];
haxe.Http.prototype = {
setParameter: function(param,value) {
this.params = Lambda.filter(this.params,function(p) {
return p.param != param;
});
this.params.push({ param : param, value : value});
return this;
}
,request: function(post) {
var me = this;
me.responseData = null;
var r = this.req = js.Browser.createXMLHttpRequest();
var onreadystatechange = function(_) {
console.log('in onreadystatechange function');
//if(r.readyState != 4) return;
console.log(r.responseText);
console.log('r.status: ' + r.status);
me.req = null;
me.onData(me.responseData = r.responseText);
};
if(typeof XDomainRequest != "undefined") {
console.log('XDomainRequest');
r.onload = onreadystatechange;
}
var uri = this.postData;
try {
console.log('calling r.open with url: ' + this.url);
r.open("GET",this.url);
} catch( e1 ) {
me.req = null;
this.onError(e1.toString());
return;
}
//r.send(uri);
//do it, wrapped in timeout to fix ie9
setTimeout(function () {
r.send();
}, 0);
//if(!this.async) onreadystatechange(null);
}
,onData: function(data) {
}
,onError: function(msg) {
}
,onStatus: function(status) {
}
,__class__: haxe.Http
};
Note that this only implements the IE9 fix without doing the if statements to keep support for other browsers. But it's really easy. the IF statement is simply
if(typeof XDomainRequest != "undefined") return new XDomainRequest();
Basically, I know what the issue is, I just have no idea how I can change these things within the core of Haxe itself.
Thanks.
https://github.com/HaxeFoundation/haxe/pull/3449
BAM! Got it working in a local version of my haxe. Fixed for all browsers and sent a pull request. :D
Good job on this one!
You have to contact the Haxe mailing list directly, most thinking heads are over there rather than here :)
https://groups.google.com/d/forum/haxelang

nodejs json.stringify a 1gb object running out of memory

I'm trying to json.stringify a 1 gb object so that I can write it to disk. I get FATAL ERROR: JS Allocation failed - process out of memory
What can I do to stringify successfully?
You can stringify bit by bit manually: if y is a key of x, then JSON.stringify(y) + ":" + JSON.stringify(x[y]) gives you one segment.
Using fs.appendFileSync, for example, you can use:
var output = "out.json";
fs.writeFileSync(output, "{");
var first = true;
for(var y in x) {
if(x.hasOwnProperty(y)) {
if(first) first = false;
else fs.appendFileSync(output, ",");
fs.appendFileSync(output, JSON.stringify(y) + ":" + JSON.stringify(x[y]))
}
}
fs.appendFileSync(output, "}");
You can also use a Write Stream
Extended with Object, Array checker
var first, y, i$, ref$, len$, toString$ = {}.toString;
switch (toString$.call(x).slice(8, -1)) {
case 'Object':
fs.writeFileSync(output, '{');
first = true;
for (y in x) {
if (x.hasOwnProperty(y)) {
if (first) {
first = false;
} else {
fs.appendFileSync(output, ',');
}
fs.appendFileSync(output, JSON.stringify(y) + ':' + JSON.stringify(x[y]));
}
}
fs.appendFileSync(output, '}');
break;
case 'Array':
fs.writeFileSync(output, '[');
first = true;
for (i$ = 0, len$ = (ref$ = x).length; i$ < len$; ++i$) {
y = ref$[i$];
if (first) {
first = false;
} else {
fs.appendFileSync(output, ',');
}
fs.appendFileSync(output, JSON.stringify(y));
}
fs.appendFileSync(output, ']');
break;
default:
fs.writeFileSync(output, JSON.stringify(x));
}

firebug saying not a function

<script type = "text/javascript">
var First_Array = new Array();
function reset_Form2() {document.extraInfo.reset();}
function showList1() {document.getElementById("favSports").style.visibility="visible";}
function showList2() {document.getElementById("favSubjects").style.visibility="visible";}
function hideProceed() {document.getElementById('proceed').style.visibility='hidden';}
function proceedToSecond ()
{
document.getElementById("div1").style.visibility="hidden";
document.getElementById("div2").style.visibility="visible";
document.getElementById("favSports").style.visibility="hidden";
document.getElementById("favSubjects").style.visibility="hidden";
}
function backToFirst () {
document.getElementById("div1").style.visibility="visible";
document.getElementById("div2").style.visibility="hidden";
document.getElementById("favSports").style.visibility="visible";
document.getElementById("favSubjects").style.visibility="visible";
}
function reset_Form(){
document.personalInfo.reset();
document.getElementById("favSports").style.visibility="hidden";
document.getElementById("favSubjects").style.visibility="hidden";
}
function isValidName(firstStr) {
var firstPat = /^([a-zA-Z]+)$/;
var matchArray = firstStr.match(firstPat);
if (matchArray == null) {
alert("That's a weird name, try again");
return false;
}
return true;
}
function isValidZip(zipStr) {
var zipPat =/[0-9]{5}/;
var matchArray = zipStr.match(zipPat);
if(matchArray == null) {
alert("Zip is not in valid format");
return false;
}
return true;
}
function isValidApt(aptStr) {
var aptPat = /[\d]/;
var matchArray = aptStr.match(aptPat);
if(matchArray == null) {
if (aptStr=="") {
return true;
}
alert("Apt is not proper format");
return false;
}
return true;
}
function isValidDate(dateStr) {
//requires 4 digit year:
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
var matchArray = dateStr.match(datePat);
if (matchArray == null) {
alert("Date is not in a valid format.");
return false;
}
return true;
}
function checkRadioFirst() {
var rb = document.personalInfo.salutation;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
return true;
}
}
alert("Please specify a salutation");
return false;
}
function checkCheckFirst() {
var rb = document.personalInfo.operatingSystems;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
return true;
}
}
alert("Please specify an operating system") ;
return false;
}
function checkSelectFirst() {
if ( document.personalInfo.sports.selectedIndex == -1)
{
alert ( "Please select a sport" );
return false;
}
return true;
}
function checkRadioSecond() {
var rb = document.extraInfo.referral;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
return true;
}
}
alert("Please select form of referral");
return false;
}
function checkCheckSecond() {
var rb = document.extraInfo.officeSupplies;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
return true;
}
}
alert("Please select an office supply option");
return false;
}
function checkSelectSecond() {
if ( document.extraInfo.colorPick.selectedIndex == 0 ) {
alert ( "Please select a favorite color" );
return false;
}
return true;
}
function check_Form(){
var retvalue = isValidDate(document.personalInfo.date.value);
if(retvalue) {
retvalue = isValidZip(document.personalInfo.zipCode.value);
if(retvalue) {
retvalue = isValidName(document.personalInfo.nameFirst.value);
if(retvalue) {
retvalue = checkRadioFirst();
if(retvalue) {
retvalue = checkCheckFirst();
if(retvalue) {
retvalue = checkSelectFirst();
if(retvalue) {
retvalue = isValidApt(document.personalInfo.aptNum.value);
if(retvalue){
document.getElementById('proceed').style.visibility='visible';
var rb = document.personalInfo.salutation;
for(var i=0;i<rb.length;i++) {
if(rb[i].checked) {
var salForm = rb[i].value;
}
}
var SportsOptions = "";
for(var j=0;j<document.personalInfo.sports.length;j++){
if ( document.personalInfo.sports.options[j].selected){
SportsOptions += document.personalInfo.sports.options[j].value + " ";
}
}
var SubjectsOptions= "";
for(var k=0;k<document.personalInfo.subjects.length;k++){
if ( document.personalInfo.subjects.options[k].selected){
SubjectsOptions += document.personalInfo.subjects.options[k].value + " ";
}
}
var osBox = document.personalInfo.operatingSystems;
var OSOptions = "";
for(var y=0;y<osBox.length;y++) {
if(osBox[y].checked) {
OSOptions += osBox[y].value + " ";
}
}
First_Array[0] = salForm;
First_Array[1] = document.personalInfo.nameFirst.value;
First_Array[2] = document.personalInfo.nameMiddle.value;
First_Array[3] = document.personalInfo.nameLast.value;
First_Array[4] = document.personalInfo.address.value;
First_Array[5] = document.personalInfo.aptNum.value;
First_Array[6] = document.personalInfo.city.value;
for(var l=0; l<document.personalInfo.state.length; l++) {
if (document.personalInfo.state.options[l].selected) {
First_Array[7] = document.personalInfo.state[l].value;
}
}
First_Array[8] = document.personalInfo.zipCode.value;
First_Array[9] = document.personalInfo.date.value;
First_Array[10] = document.personalInfo.phone.value;
First_Array[11] = SportsOptions;
First_Array[12] = SubjectsOptions;
First_Array[13] = OSOptions;
alert("Everything looks good.");
document.getElementById('validityButton').style.visibility='hidden';
}
}
}
}
}
}
}
}
/*function formAction2() {
var retvalue;
retvalue = checkRadioSecond();
if(!retvalue) {
return retvalue;
}
retvalue = checkCheckSecond();
if(!retvalue) {
return retvalue;
}
return checkSelectSecond() ;
} */
</script>
This is just a sample of the code, there are alot more functions, but I thought the error might be related to surrounding code. I have absolutely no idea why, as I know all the surrounding functions execute, and First_Array is populated.
However when I click the Proceed to Second button, the onclick attribute does not execute because Firebug says proceedToSecond is not a function
button code:
<input type="button" id="proceed" name="proceedToSecond" onclick="proceedToSecond();" value="Proceed to second form">
I had the same problem, and it's because you have a form with the same name as your function. JavaScript doesn't seem to be able to distinguish between the two, so you get the "not a function" error.
Maybe there is an error in your Javascript before that snippet given by you. If so, the rest will not be parsed by Firefox and then your function will not be defined.
The problem was resolved by changing proceedToSecond() to doIt() in both the call and the function name. I have no idea why
Hmm... I always used javascript:function_name() instead of function_name() because a few times the javascript didn't run. The name tag for the html snippet might have to be changed to a slightly different name because javascript might be getting it mixed up. Can you show us the entire javascript file because there may be a mistake/syntax error somewhere at the bottom/top.
It works on my computer, Firefox 3.5.5, Firebug 1.4.3, when inserting your code into an empty html document (<html><head/><body> code </body></html>)
Maybe there is another bug somewhere in your DOM, or in some of your other functions?
Could you possibly paste the entire source here, or maybe on a pastebin site?