Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

http://singpolyma.net/

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

JavaScript var_dump (Mark 2)

Same as var_dump for PHP, but for JavaScript. Useful if you do not have Firebug.

A typical useage:

document.write(var_dump(ANY-JS-VAR,'html'));

     function var_dump(data,addwhitespace,safety,level) {
        var rtrn = '';
        var dt,it,spaces = '';
        if(!level) {level = 1;}
        for(var i=0; i<level; i++) {
           spaces += '   ';
        }//end for i<level
        if(typeof(data) != 'object') {
           dt = data;
           if(typeof(data) == 'string') {
              if(addwhitespace == 'html') {
                 dt = dt.replace(/&/g,'&amp;');
                 dt = dt.replace(/>/g,'&gt;');
                 dt = dt.replace(/</g,'&lt;');
              }//end if addwhitespace == html
              dt = dt.replace(/\"/g,'\"');
              dt = '"' + dt + '"';
           }//end if typeof == string
           if(typeof(data) == 'function' && addwhitespace) {
              dt = new String(dt).replace(/\n/g,"\n"+spaces);
              if(addwhitespace == 'html') {
                 dt = dt.replace(/&/g,'&amp;');
                 dt = dt.replace(/>/g,'&gt;');
                 dt = dt.replace(/</g,'&lt;');
              }//end if addwhitespace == html
           }//end if typeof == function
           if(typeof(data) == 'undefined') {
              dt = 'undefined';
           }//end if typeof == undefined
           if(addwhitespace == 'html') {
              if(typeof(dt) != 'string') {
                 dt = new String(dt);
              }//end typeof != string
              dt = dt.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
           }//end if addwhitespace == html
           return dt;
        }//end if typeof != object && != array
        for (var x in data) {
           if(safety && (level > safety)) {
              dt = '*RECURSION*';
           } else {
              try {
                 dt = var_dump(data[x],addwhitespace,safety,level+1);
              } catch (e) {continue;}
           }//end if-else level > safety
           it = var_dump(x,addwhitespace,safety,level+1);
           rtrn += it + ':' + dt + ',';
           if(addwhitespace) {
              rtrn += '\n'+spaces;
           }//end if addwhitespace
        }//end for...in
        if(addwhitespace) {
           rtrn = '{\n' + spaces + rtrn.substr(0,rtrn.length-(2+(level*3))) + '\n' + spaces.substr(0,spaces.length-3) + '}';
        } else {
           rtrn = '{' + rtrn.substr(0,rtrn.length-1) + '}';
        }//end if-else addwhitespace
        if(addwhitespace == 'html') {
           rtrn = rtrn.replace(/ /g,"&nbsp;").replace(/\n/g,"<br>");
        }//end if addwhitespace == html
        return rtrn;
     }//end function var_dump

NP Problem Solution

Taken from hoodwink.d on http://xkcd.com/c287.html

items = ["Mixed Fruit", "French Fries", "Side Salad", "Hot Wings", "Mozzarella Sticks", "Sampler Plate"]
prices = [2.15, 2.75, 3.35, 3.55, 4.20, 5.80]

solution = []
sum = 0
loop do
    break if sum == 15.05
    if sum > 15.05
        solution = []
        sum = 0
        next
    else
        choice = rand prices.length
        sum += prices[choice]
        solution << items[choice]
    end
end

p "A solution is: #{solution.inspect}" 

var_dump for javascript

hackish implementation of the php 'var_dump()' in javascript:

function var_dump(obj) {
   if(typeof obj == "object") {
      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
   } else {
      return "Type: "+typeof(obj)+"\nValue: "+obj;
   }
}//end function var_dump

Flat-tag updater

Pass new tags followed by a table name and database handle and this function updates the table so that each tag becomes properly associated/its record created, eg:

table state:
tagname | relatedtags
-----------------------
blog | rss;personal
rss | blog
personal | blog

call (table is named tags):
updateTags("blog personal friends","tags",$db);

table state:
tagname | relatedtags
-----------------------
blog | rss;personal;friends
rss | blog
personal | blog;friends
friends | blog;personal


function updateTags($tags,$table,$db) {//category handling stuff
   include("recordExists.php");//see http://bigbold.com/snippets/posts/show/464
   $cats = explode(";",$tags);//parse tags into array cats
   foreach($cats as $cat) {//loop through cats
      $tmp = array($cat);//dummy array with cat in it
      $tmp = array_diff($cats,$tmp);//get everything in cats that is not cat
      if(!recordExists("tagname",$cat,$table,$db)) {//if there is no category by this name yet
         $tmp = implode(";",$tmp);//make tmp into semicolon-separated string
         $result = mysql_query("INSERT INTO ".$table." (tagname,relatedtags) VALUES ('$cat','$tmp')", $db) or die(mysql_error());//insert category into database
      } else {
         $result = mysql_query("SELECT relatedtags FROM ".$table." WHERE tagname='$cat'", $db) or die(mysql_error());//select already related tags
         $result = mysql_fetch_array($result);//get the result row as an array
         $result = explode(";",$result['relatedtags']);//parse relatedtags into result
         $result = array_merge($tmp,$result);//merge the cats in this $tags (without cat, hence tmp) with the ones that were in there already
         $result = array_unique($result);//strip duplicates
         $result = implode(";",$result);//make result into semicolon-separated string
         $result = mysql_query("UPDATE ".$table." SET relatedtags='$result' WHERE tagname='$cat'", $db) or die(mysql_error());//update category
      }//end if-else !recordExists
   }//end foreach cats
}//end function updateTags

Record Exists

In mySQL (from PHP), checks for the existance of a record based on id, passing the name of the id field followed by the id to check for, the table name, and the database resource, in that order.
function recordExists($id,$idval,$table,$db) {//check for id=idval in table and return TRUE or FALSE
   $result = mysql_query("SELECT * FROM ".$table." WHERE ".$id."='".$idval."'", $db) or die(mysql_error());
   if($row = mysql_fetch_array($result)) {//if we did return a record
      return 1;
   }//end if row
   return 0;
}//end fuction recordExists
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS