<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JSON &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/json/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>Computer Algorithms: Data Compression with Relative Encoding</title>
		<link>/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/</link>
		<comments>/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/#comments</comments>
		<pubDate>Mon, 30 Jan 2012 18:27:26 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Africa]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[Algorithmic efficiency]]></category>
		<category><![CDATA[Application This algorithm]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[San Francisco]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[web server]]></category>
		<category><![CDATA[west coast]]></category>
		<category><![CDATA[Yahoo! Communications Europe Ltd.]]></category>

		<guid isPermaLink="false">/?p=2658</guid>
		<description><![CDATA[Overview Relative encoding is another data compression algorithm. While run-length encoding, bitmap encoding and diagram and pattern substitution were trying to reduce repeating data, with relative encoding the goal is a bit different. Indeed run-length encoding was searching for long runs of repeating elements, while pattern substitution and bitmap encoding were trying to “map” where &#8230; <a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Relative Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>Relative encoding is another data compression algorithm. While <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">run-length encoding</a>, <a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" title="Computer Algorithms: Data Compression with Bitmaps">bitmap encoding</a> and <a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">diagram and pattern substitution</a> were trying to reduce repeating data, with relative encoding the goal is a bit different. Indeed run-length encoding was searching for long runs of repeating elements, while pattern substitution and bitmap encoding were trying to “map” where the repetitions happen to occur. </p>
<p>The only problem with these algorithms is that not always the input stream of data is constructed out of repeating elements. It is clear that if the input stream contains many repeating elements there must be some way of reducing them. However that doesn’t mean that we cannot compress data if there are no repetitions. It all depends on the data. Let’s say we have the following stream to compress.</p>
<pre lang="PHP">
1, 2, 3, 4, 5, 6, 7
</pre>
<p>We can hardly imagine how this stream of data can be compressed. The same problem may occur when trying to compress the alphabet. Indeed the alphabet letters the very base of the words so it is the minimal part for word construction and it&#8217;s hard to compress them.</p>
<p>Fortunately this isn’t true always. An algorithm that tryies to deal with non repeating data is relative encoding. Let’s see the following input stream &#8211; years from a given decade (the 90&#8217;s).</p>
<pre lang="PHP">
1991,1991,1999,1998,1991,1993,1992,1992
</pre>
<p>Here we have 39 characters and we can reduce them. A natural approach is to remove the leading “19” as we humans often do.</p>
<pre lang="PHP">
91,91,99,98,91,93,92,92
</pre>
<p>Now we have a shorter string, but we can go even further with keeping only the first year. All other years will as relative to this year.</p>
<pre lang="PHP">
91,0,8,7,0,2,1,1
</pre>
<p>Now the volume of transferred data is reduced a lot (from 39 to 16 &#8211; more than 50%). However there are some questions we need to answer first, because the stream wont be always formatted in such pretty way. How about the next character stream?</p>
<pre lang="PHP">
91,94,95,95,98,100,101,102,105,110
</pre>
<p>We see that the value 100 is somehow in the middle of the interval and it is handy to use it as a base value for the relative encoding. Thus the stream above will become:</p>
<pre lang="PHP">
-9,-6,-5,-5,-2,100,1,2,5,10
</pre>
<p>The problem is that we can’t decide which value will be the <strong>base value</strong> so easily. What if the data was dispersed in a different way.</p>
<pre lang="PHP">
96,97,98,99,100,101,102,103,999,1000,1001,1002
</pre>
<p>Now the value of “100” isn’t useful, because compressing the stream will get something like this:</p>
<pre lang="PHP">
-4,-3,-2,-1,100,1,2,3,899,900,901,902
</pre>
<p>To group the relative values around “some” base values will be far more handy.</p>
<pre lang="PHP">
(-4,-3,-2,-1,100,1,2,3)(-1,1000,1,2)
</pre>
<p>However to decide which value will be the base value isn’t that easy. Also the encoding format is not so trivial. In the other hand this type of encoding can be useful in som specific cases as we can see bellow.<br />
<span id="more-2658"></span></p>
<h2>Implementation</h2>
<p>The implementation of this algorithm depends on the specific task and the format of the data stream. Assuming that we’ve to transfer the stream of years in JSON from a web server to a browser, here’s a short PHP snippet.</p>
<pre lang="PHP">
// JSON: [1991,1991,1999,1998,1999,1998,1995,1997,1994,1993]
$years = array(1991,1991,1999,1998,1999,1998,1995,1997,1994,1993);

function relative_encoding($input)
{
	$output = array();
	$inputLength = count($input);
	
	$base = $input[0];
	
	$output[] = $base;
	
	for ($i = 1; $i < $inputLength; $i++) {
		$output[] = $input[$i] - $base;
	}
	
	return $output;
}

// JSON: [1991,0,8,7,8,7,4,6,3,2]
echo json_encode(relative_encoding($years));
</pre>
<h2>Application</h2>
<p>This algorithm may be very useful in many cases, but here’s one of them. There are plenty of map applications around the web. Some products as <a href="http://maps.google.com/" title="Google Maps" target="_blank">Google Maps</a>, <a href="http://maps.yahoo.com/" title="Yahoo! Maps" target="_blank">Yahoo! Maps</a>, <a href="http://www.bing.com/maps/" title="Bing Maps" target="_blank">Bing Maps</a> are quite famous, while there are very useful open source projects as <a href="http://www.openstreetmap.org/" title="OpenStreetMap" target="_blank">OpenStreetMap</a>. The web sites using these apps are thousands. </p>
<p>A typical use case is to transfer lots of Geo coordinates from web server to a browser using JSON. Indeed any GEO point on Earth is relative to the point (0,0), which is located near the west coast of Africa, however on large zoom levels, when there are tons of markers we can transfer the information with relative encoding.</p>
<p>For instance the following diagram shows San Francisco with some markers on it. Their coordinates are be relative to the point (0,0) on Earth.</p>
<figure id="attachment_2682" style="width: 819px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/FullLatLononSanFrancisco.png"><img src="/wp-content/uploads/2012/01/FullLatLononSanFrancisco.png" alt="San Francisco map with full lat and lon markers" title="FullLatLononSanFrancisco" width="819" height="456" class="size-full wp-image-2682" srcset="/wp-content/uploads/2012/01/FullLatLononSanFrancisco.png 819w, /wp-content/uploads/2012/01/FullLatLononSanFrancisco-300x167.png 300w" sizes="(max-width: 819px) 100vw, 819px" /></a><figcaption class="wp-caption-text">Map markers can be relative to the (0, 0) point on Earth, which can be sometimes useless.</figcaption></figure>
<p>Far more useful may be to encode those markers, relative to the center of the city, thus we can save some space.</p>
<figure id="attachment_2681" style="width: 819px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/SanFranciscoMap.png"><img src="/wp-content/uploads/2012/01/SanFranciscoMap.png" alt="San Francisco map with relative encoded markers" title="SanFranciscoMap" width="819" height="456" class="size-full wp-image-2681" srcset="/wp-content/uploads/2012/01/SanFranciscoMap.png 819w, /wp-content/uploads/2012/01/SanFranciscoMap-300x167.png 300w" sizes="(max-width: 819px) 100vw, 819px" /></a><figcaption class="wp-caption-text">Relative encoding can be useful for map markers on large zoom level!</figcaption></figure>
<p>However this type of compression can be tricky, for example when dragging the map and updating the marker array. In the other hand we must group markers if we have to load more than one city. That’s why we must be careful when implementing it. But in the other hand it can be very useful - for instance on initial load of the map we can reduce data and speed up the load time. </p>
<p>The thing is that with relative encoding we can save only changes to base value (data) - something like version control systems and thus reducing data transfer and load. Here's a graphical example. In the first case on the diagram bellow we can see that each item is stored on its own. It doesn't depend on the adjacent items and it can be completely independent of them.</p>
<figure id="attachment_2694" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_11.png"><img src="/wp-content/uploads/2012/01/chart_11.png" alt="Non-relative encoding" title="Non-relative encoding" width="600" height="371" class="size-full wp-image-2694" srcset="/wp-content/uploads/2012/01/chart_11.png 600w, /wp-content/uploads/2012/01/chart_11-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>However we can keep full info only for the first item and any other item will be relative to it, like on the diagram bellow.</p>
<figure id="attachment_2695" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_21.png"><img src="/wp-content/uploads/2012/01/chart_21.png" alt="Relative encoding" title="Relative encoding" width="600" height="371" class="size-full wp-image-2695" srcset="/wp-content/uploads/2012/01/chart_21.png 600w, /wp-content/uploads/2012/01/chart_21-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/02/06/computer-algorithms-data-compression-with-prefix-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Prefix Encoding">Computer Algorithms: Data Compression with Prefix Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Bitmaps</title>
		<link>/2012/01/16/computer-algorithms-data-compression-with-bitmaps/</link>
		<comments>/2012/01/16/computer-algorithms-data-compression-with-bitmaps/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 09:35:24 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[bitmap]]></category>
		<category><![CDATA[bitmap compressing algorithm]]></category>
		<category><![CDATA[Bzip2]]></category>
		<category><![CDATA[Coding theory]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[gif]]></category>
		<category><![CDATA[Graphics file formats]]></category>
		<category><![CDATA[image compression]]></category>
		<category><![CDATA[Information theory]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=2604</guid>
		<description><![CDATA[Overview In my previous post we saw how to compress data consisting of very long runs of repeating elements. This type of compression is known as &#8220;run-length encoding&#8221; and can be very handy when transferring data with no loss. The problem is that the data must follow a specific format. Thus the string “aaaaaaaabbbbbbbb” can &#8230; <a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Bitmaps</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Overview</h2>
<p>In <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" title="Computer Algorithms: Data Compression with Run-length Encoding">my previous post</a> we saw how to compress data consisting of very long runs of repeating elements. This type of compression is known as &#8220;run-length encoding&#8221; and can be very handy when transferring data with no loss. The problem is that the data must follow a specific format. Thus the string <strong>“aaaaaaaabbbbbbbb”</strong> can be compressed as <strong>“a8b8”</strong>. Now a string with length 16 can be compressed as a string with length 4, which is 25% of its initial length without loosing any information. There will be a problem in case the characters (elements) were dispersed in a different way. What would happen if the characters are the same, but they don’t form long runs? What if the string was <strong>“abababababababab”</strong>? The same length, the same characters, but we cannot use run-length encoding! Indeed using this algorithm we’ll get at best the same string.</p>
<p>In this case, however, we can see another fact. The string consists of too many repeating elements, although not arranged one after another. We can compress this string with a bitmap. This means that we can save the positions of the occurrences of a given element with a sequence of bits, which can be easily converted into a decimal value. In the example above the string <strong>“abababababababab”</strong> can be compressed as <strong>“1010101010101010”</strong>, which is <strong>43690</strong> in decimals, and even better <strong>AAAA</strong> in hexadecimal. Thus the long string can be compressed. When decompressing (decoding) the message we can convert again from decimal/hexadecimal into binary and match the occurrences of the characters. Well, the example above is too simple, but let’s say only one of the characters is repeating and the rest of the string consists of different characters like this: <strong>“abacadaeafagahai”</strong>. Then we can use bitmap only for the character “a” &#8211; <strong>“1010101010101010”</strong> and compress it as <strong>“AAAA bcdefghi”</strong>. As you can see all the example strings are exactly 16 characters and that is a limitation. To use bitmaps with variable length of the data is a bit tricky and it is not always easy (if possible) to decompress it.</p>
<p><figure id="attachment_2624" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression.png"><img src="/wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression.png" alt="Bitmap Compression" title="Bitmap Compression" width="620" class="size-full wp-image-2624" srcset="/wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression.png 1140w, /wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression-300x160.png 300w, /wp-content/uploads/2012/01/Run-lengthvs.BitmapCompression-1024x547.png 1024w" sizes="(max-width: 1140px) 100vw, 1140px" /></a><figcaption class="wp-caption-text">Basically bitmap compression saves the positions of an element that is repeated very often in the message!</figcaption></figure><br />
<span id="more-2604"></span><br />
In the other hand bitmap compression  is not only applicable on strings. We can compress also arrays, objects or any kind of data. The example from my previous post is very suitable. Then we had to transfer a large array from a server to the client (browser) using <a href="/tag/json/" title="JSON on stoimen.com/blog">JSON</a>. The data then was very suitable for “run-length encoding”. Now let’s assume we have the same data &#8211; a set of different years, which this time are dispersed in a different way. </p>
<pre lang="PHP">
$data = array(
	0 	=> 1991,
	1 	=> 1992,
	2 	=> 1993,
	3 	=> 1994,
	4 	=> 1991,
	5 	=> 1992,
	6 	=> 1993,
	7 	=> 1992,
	8 	=> 1991,
	9 	=> 1991,
	10 	=> 1991,
	11 	=> 1992,
	12 	=> 1992,
	13 	=> 1991,
	14 	=> 1991,
	15 	=> 1992,	
	...
);
</pre>
<p>The JSON will encoded message will be the following (a simple but yet very large javascript array).</p>
<pre lang="PHP">
[1991,1992,1993,1994,1991,1992,1993,1992,1991,1991,1991,1992,1992,1991,1991,1992, ...]
</pre>
<p>However if we use bitmap compression we’ll get a &#8220;shorter&#8221; array.</p>
<pre lang="PHP">
$data = array(
	0 => array(1991, '1000100011100110'),
	1 => array(1992, '0100010100011001'),
	2 => array(1993, '0010001000000000'),
	3 => array(1994, '0001000000000000'),
);
</pre>
<p>Now the JSON is:</p>
<pre lang="PHP">
[[1991,"1000100011100110"],[1992,"0100010100011001"],[1993,"0010001000000000"],[1994,"0001000000000000"]]
</pre>
<p>It is obvious that the compression ratio is getting better and better as the uncompressed data grows. In fact, most of us know bitmap compression from images, because this algorithm is largely used for image compression. We can imagine how successful it can be when compressing black and white images (as black and white can be represented as 0 and 1s). Actually it is used for more than two colors (256 for instance) and again the level of compression is very high.</p>
<h2>Implementation</h2>
<p>The following implementation on <a href="/category/php/" title="PHP on stoimen.com">PHP</a> aims only to illustrate the bitmap compressing algorithm. As we know this algorithm can be applicable for any kind of data structures. </p>
<pre lang="PHP">
// too many repeating "a" characters
$msg = 'aazahalavaatalawacamaahakafaaaqaaaiauaacaaxaauaxaaaaaapaayatagaaoafaawayazavaaaazaaabararaaaaakakaaqaarazacajaazavanazaaaeanaaoajauaaaaaxalaraaapabataaavaaab';

function bitmap($message) 
{
	$i = 0;
	$bits = $rest = '';
	
	while ($v = $message[$i]) {
		if ($v == 'a') {
			$bits .= '1';
		} else {
			$bits .= '0';
			$rest .= $v;
		}
		$i++;
	}
	
	return number_format(bindec($bits), 0, '.', '') . $rest;;
}

echo bitmap($msg);

// uncompressed: 
acaaaaadaaaabalaaeaaaaganaaxakaavawamaasavajawaaaayaauaaadalanagaeaeamaarafalaazaaaiasaanaahaaazaraxaalaahaaawaaajasamahaajaakarapanaakaoakaanawalaacamauaamaal
// compressed:
152299251941730035874325065523548237677352452096zhlvtlwcmhkfqiucxuxpytgofwyzvzbrrkkqrzcjzvnzenojuxlrpbtvb
</pre>
<h2>Application</h2>
<p>This algorithm is very useful when there is an element in our data that repeats very often, so you need to investigate the nature of the data you want to compress. Actually because of this fact this algorithm is used for image compression as <a href="http://en.wikipedia.org/wiki/Portable_Network_Graphics" title="Portable Network Graphics" target="_blank">PNG8</a> or <a href="http://en.wikipedia.org/wiki/Graphics_Interchange_Format" title="Graphics Interchange Format" target="_blank">GIF</a>.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Run-length Encoding">Computer Algorithms: Data Compression with Run-length Encoding </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/16/computer-algorithms-data-compression-with-bitmaps/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Data Compression with Run-length Encoding</title>
		<link>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/</link>
		<comments>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 09:08:06 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Algorithmic efficiency]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[Bzip2]]></category>
		<category><![CDATA[Data compression]]></category>
		<category><![CDATA[data compression algorithm]]></category>
		<category><![CDATA[data compression algorithms]]></category>
		<category><![CDATA[faster services]]></category>
		<category><![CDATA[Google Inc.]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Lossless data compression]]></category>
		<category><![CDATA[lossless data compression algorithm]]></category>
		<category><![CDATA[Lossy compression]]></category>
		<category><![CDATA[programmer]]></category>
		<category><![CDATA[run-length algorithm]]></category>
		<category><![CDATA[Run-length encoding]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[This algorithm]]></category>
		<category><![CDATA[virtual machine]]></category>
		<category><![CDATA[web server]]></category>

		<guid isPermaLink="false">/?p=2594</guid>
		<description><![CDATA[Introduction No matter how fast today&#8217;s computers and networks are, the users will constantly need faster and faster services. To reduce the volume of the transferred data we usually use some sort of compression. That is why this computer sciences area will be always interesting to research and develop. There are many data compression algorithms, &#8230; <a href="/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Data Compression with Run-length Encoding</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>No matter how fast today&#8217;s computers and networks are, the users will constantly need faster and faster services. To reduce the volume of the transferred data we usually use some sort of compression. That is why this computer sciences area will be always interesting to research and develop.</p>
<p>There are many data compression algorithms, some of them lossless, others lossy, but their main goal aways will be to spare storage space and traffic. These algorithms are very useful when talking about data transfer between two distant places. Perhaps the best example is the transfer between a web server and a browser.</p>
<p>In the last few years a lot of research has been done on compressing files, executed on the client side. Such files are javascript, css, htmls and images. In fact servers and clients already have some techniques to compress data, like using <a href="http://www.gzip.org/" title="The gzip home page" target="_blank">GZIP</a> for instance, that can dramatically decrease the transfer. In the other hand there are lots of tools and tricks in order to decrease the size of the data.</p>
<p>Actually when a file is executed by the client&#8217;s virtual machine, it doesn&#8217;t matter how &#8220;beautifully&#8221; it is formatted from a programmer&#8217;s point of view. Thus the spaces, tabs and the new lines don&#8217;t bring any significant information for the environment. That is why such compressing tools like <a href="http://developer.yahoo.com/yui/compressor/" title="YUI Compressor" target="_blank">YUI Compressor</a>, <a href="http://code.google.com/closure/compiler/" title="Closure Compiler - Google Code" target="_blank">Google Closure Compiler</a>, etc. remove those symbols. Well, they can achieve even more in order to improve the compression rate. In this post I won&#8217;t cover this, but this shows how important data compression algorithms are.</p>
<p>It would be great if we could just compress data with some tool. Unfortunately this is not the case and usually the compression rate depends on the data itself. It is obvious that the choice of data compression algorithm depends mainly on the data and first of all we must explore the data.</p>
<p>Here I&#8217;ll cover one very simple lossless data compression algorithm called &#8220;run-length encoding&#8221; that can be very useful in some cases.</p>
<figure id="attachment_2618" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/Run-lengthEncoding1.png"><img src="/wp-content/uploads/2012/01/Run-lengthEncoding1.png" alt="Run-length Encoding" title="Run-length Encoding" width="620" class="size-full wp-image-2618" srcset="/wp-content/uploads/2012/01/Run-lengthEncoding1.png 978w, /wp-content/uploads/2012/01/Run-lengthEncoding1-300x129.png 300w" sizes="(max-width: 978px) 100vw, 978px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h2>Overview</h2>
<p>This algorithm consists of replacing large sequences of repeating data with only one item of this data followed by a counter showing how many times this item is repeated. To become clearer let’s see a string example.</p>
<pre lang="PHP">
aaaaaaaaaabbbaxxxxyyyzyx
</pre>
<p>This string&#8217;s length is <strong>24</strong> and as we can see there are lots of repetitions. Using the run-length algorithm, we replace any run with shorter string followed by a counter.</p>
<pre lang="PHP">
a10b3a1x4y3z1y1x1
</pre>
<p>The length of this string is <strong>17</strong>, which is approximately <strong>70%</strong> of the initial length. <span id="more-2594"></span>Obviously this is not the optimal way to compress the given string. For instance we don&#8217;t need to use the digit “1” when the character is repeated only once. In some cases this approach can increase the length of the initial string which is exactly the opposite of what we need. In this case we’ll get the string bellow.</p>
<pre lang="PHP">
a10b3ax4y3zyx
</pre>
<p>Now the length of the resulting string is <strong>13</strong>, which is <strong>54%</strong> of the initial length! A variation of the example above is not to keep a counter of the repetitions of the character, but their position instead. Thus the initial string will be compressed as follows.</p>
<pre lang="PHP">
a0b10a13x14y18z21y22x23
</pre>
<p>Which of these two approaches you&#8217;ll use depends on the goal. In the second case we can achieve a good optimization of <a href="/2011/12/26/computer-algorithms-binary-search/" title="Computer Algorithms: Binary Search">binary search</a>.</p>
<p>It is clear that this algorithm is not only applicable on strings. We can achieve very good results on arrays. A typical example is the transfer of <a href="http://www.json.org/" title="JSON" target="_blank">JSON</a> from a server to a client. Then if there are large sequences of repeating data we can achieve great results.</p>
<h2>Implementation</h2>
<p>The implementation bellow is assuming that we&#8217;re compressing a string and it&#8217;s written on PHP. However the nature of this algorithm doesn&#8217;t restrict us to use only strings. As I said before with slight modifications we can use it with other data structures. It is important only to understand that the run-length algorithm is very useful on large sequences of repeating elements, no matter characters or array items.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = $j = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
			
			if ($i) 
				$output .= $j;
				
			$output .= $msg[$i];
				
			$prev = $msg[$i];
			
			$j = 0;
		}
		$j++;
		$i++;
	}
	
	$output .= $j;
	
	return $output;
}

// a10b3a1x4y3z1y1x1
echo run_length_encode($message);
</pre>
<p>And slightly optimized.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = $j = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
			
			if ($i && $j > 1) 
				$output .= $j;
				
			$output .= $msg[$i];
				
			$prev = $msg[$i];
			
			$j = 0;
		}
		$j++;
		$i++;
	}
	
	if ($j > 1)
		$output .= $j;
	
	return $output;
}

// a10b3ax4y3zyx
echo run_length_encode($message);
</pre>
<p>Finally a small change &#8211; now we store the position of the character.</p>
<pre lang="PHP">
$message = 'aaaaaaaaaabbbaxxxxyyyzyx';

function run_length_encode($msg)
{
	$i = 0;
	$prev = '';
	$output = '';
	
	while ($msg[$i]) {
		if ($msg[$i] != $prev) {
				
			$output .= $msg[$i] . $i;
				
			$prev = $msg[$i];
			
		}

		$i++;
	}
	
	return $output;
}

// a0b10a13x14y18z21y22x23
echo run_length_encode($message);
</pre>
<h2>Complexity and Data Compression</h2>
<p>We&#8217;re used to talk about complexity of an algorithm measuring time and we usually try to find the fastest implementation, like in search algorithms. Here it is not so important to compress data quickly, but to compress as much as possible so the output is as small as possible without lossing data. A great feature of run-length encoding is that this algorithm is easy to implement.</p>
<h2>Application</h2>
<p>We can use run-length encoding in many cases. It is commonly used to compress images and is very successful when we deal only with black and white images. Here I&#8217;ll cover another use case that I only mentioned above. Let&#8217;s say we have to transfer a very large array of data to our AJAX-powered application using JSON. Let&#8217;s say also that the data are some years, for instance the years of the premiere of a movie. There are lots of movies with a premiere in the same year, thus although the data is sorted, we actually can&#8217;t have any benefit. More important is that we have large sequences of data. Here we can use run-length encoding.</p>
<pre lang="PHP">
$data = array(
	0 	=> 1991,
	1 	=> 1991,
	...
	2223 	=> 1991,
	2224 	=> 1992,
	...
	19298 	=> 1995,
	19299 	=> 1996,
	...
);
</pre>
<p>As you can see to transfer the whole array can be a nightmare, especially on slow networks. It is better to compress it (i.e. with PHP&#8217;s <a href="http://php.net/manual/en/function.json-encode.php" title="PHP: json_encode" target="_blank">json_encode</a>).</p>
<pre lang="PHP">
// {"0":1991,"1":1991, ..., "2223":1991,"2224":1992, ..., "19298":1995,"19299":1996, ...}
echo json_encode($data);
</pre>
<p>After running run-length encoding we can receive something like the following array (note that these are only sample data and it&#8217;s up to you to decide which is the best format to store data).</p>
<pre lang="PHP">
$data = array(
	0 => array(1991, 2224),
	1 => array(1992, 3948),
	2 => array(1995, 2398),
	3 => array(1996, 3489),
);
</pre>
<p>And the JSON output.</p>
<pre lang="PHP">
// [[1991,2224],[1992,3948],[1995,2398],[1996,3489]]
echo json_encode($data);
</pre>
<p>Note that if the data is sorted we can achieve great success compressing it!!! This approach can be used for images, graphics or map coordinates.</p>
<p>This is only one example of how data compression can be useful in our daily work. Although the communication between the server and the client can be optimized and compressed, we can improve it. In other words we&#8217;re not always sure that the opposite side supports compression.</p>
<p>Well, it&#8217;s true that the client has to decompress the data, which can also be slow. Now in the first case we have only the time to transfer, as on the diagram bellow.</p>
<figure id="attachment_2609" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png"><img src="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png" alt="Data Transfer Without Compression" title="Data Transfer Without Compression" width="620" class="size-full wp-image-2609" srcset="/wp-content/uploads/2012/01/DataTransferWithoutCompression.png 957w, /wp-content/uploads/2012/01/DataTransferWithoutCompression-300x54.png 300w" sizes="(max-width: 957px) 100vw, 957px" /></a><figcaption class="wp-caption-text">Time to transfer data without compression!</figcaption></figure>
<p>In the second case, we should sum the time for compression, transfer and decompression.</p>
<figure id="attachment_2610" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/DataTransferwithCompression.png"><img src="/wp-content/uploads/2012/01/DataTransferwithCompression.png" alt="Data Transfer with Compression" title="Data Transfer with Compression" width="620" class="size-full wp-image-2610" srcset="/wp-content/uploads/2012/01/DataTransferwithCompression.png 953w, /wp-content/uploads/2012/01/DataTransferwithCompression-300x59.png 300w" sizes="(max-width: 953px) 100vw, 953px" /></a><figcaption class="wp-caption-text">Time to send data with compression!</figcaption></figure>
<p>All this is important, but in general data compression can be handy in many cases in our daily work. </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/05/03/computer-algorithms-lossy-image-compression-with-run-length-encoding/" rel="bookmark" title="Computer Algorithms: Lossy Image Compression with Run-Length Encoding">Computer Algorithms: Lossy Image Compression with Run-Length Encoding </a></li>
<li><a href="/2012/01/30/computer-algorithms-data-compression-with-relative-encoding/" rel="bookmark" title="Computer Algorithms: Data Compression with Relative Encoding">Computer Algorithms: Data Compression with Relative Encoding </a></li>
<li><a href="/2012/01/16/computer-algorithms-data-compression-with-bitmaps/" rel="bookmark" title="Computer Algorithms: Data Compression with Bitmaps">Computer Algorithms: Data Compression with Bitmaps </a></li>
<li><a href="/2012/01/23/computer-algorithms-data-compression-with-diagram-encoding-and-pattern-substitution/" rel="bookmark" title="Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution">Computer Algorithms: Data Compression with Diagram Encoding and Pattern Substitution </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/09/computer-algorithms-data-compression-with-run-length-encoding/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Object Oriented JavaScript: Inheritance</title>
		<link>/2011/05/30/object-oriented-javascript-inheritance/</link>
		<comments>/2011/05/30/object-oriented-javascript-inheritance/#comments</comments>
		<pubDate>Mon, 30 May 2011 09:43:53 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[web development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Class]]></category>
		<category><![CDATA[code sample]]></category>
		<category><![CDATA[code snippet]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[Inheritance]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Literal]]></category>
		<category><![CDATA[object oriented]]></category>
		<category><![CDATA[Object-oriented programming]]></category>
		<category><![CDATA[objects]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[oop javascript]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Software engineering]]></category>

		<guid isPermaLink="false">/?p=2314</guid>
		<description><![CDATA[Objects and JavaScript JavaScript, being a functional language, differs from most of the procedural/object oriented languages we know. The object oriented approach in JavaScript is rather strange. However there is much power in making objects! The syntax is really odd and there are several approaches. Literal Notation As many of you may know the most &#8230; <a href="/2011/05/30/object-oriented-javascript-inheritance/" class="more-link">Continue reading <span class="screen-reader-text">Object Oriented JavaScript: Inheritance</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/03/02/javascript-inheritance-example/" rel="bookmark" title="JavaScript inheritance example">JavaScript inheritance example </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Objects and JavaScript</h2>
<p><a href="/tag/javascript/" title="JavaScript on Stoimen.com">JavaScript</a>, being a functional language, differs from most of the procedural/object oriented languages we know. The object oriented approach in JavaScript is rather strange. However there is much power in making objects! The syntax is really odd and there are several approaches.</p>
<h2>Literal Notation</h2>
<p>As many of you may know the most used notation is the JSON (JavaScript Object Notation).</p>
<pre lang="javascript">
{ 'key1' : 'val1'
, 'key2' : 'val2'
, 'key3' : 'val3'
}
</pre>
<p>Of course this is the very basic example. You can use as value any JavaScript object &#8211; another similar object or a function.</p>
<pre lang="javascript">
{ 'key1' : 'val1'
, 'key2' : { 'inner_key1' : 'inner_val1' }
, 'key3' : function() {
			return 10 + 5;
		 }
}
</pre>
<p>The two examples above are showing an anonymous object in JavaScript, but you can assign this code to some variable.</p>
<pre lang="javascript">
var myObject = 
	{ 'key1' : 'val1'
	, 'key2' : 'val2'
	, 'key3' : 'val3'
	}
</pre>
<p>or </p>
<pre lang="javascript">
var myObject =
	{ 'key1' : 'val1'
	, 'key2' : { 'inner_key1' : 'inner_val1' }
	, 'key3' : function() {
				return 10 + 5;
			 }
	}
</pre>
<p>and then you can call the properties of these objects with the &#8216;.&#8217; operator:</p>
<pre lang="javascript">
myObject.key1;
myObject.key2.inner_key1;
myObject.key3();
</pre>
<p>So far so good &#8211; this is the literal object notation in JavaScript. However there is another &#8220;objects&#8221; in JavaScript.<br />
<span id="more-2314"></span></p>
<h2>Objects and Functions in JavaScript</h2>
<p>Actually in JS the functions are also objects (classes). So you can define a function and then define another function inside or use the &#8220;this&#8221; operator.</p>
<pre lang="javascript">
var a = function(name)
{
	this.name = name;
	
	this.print = function() {
		alert(this.name);	
	}
}
</pre>
<p>Then you can make a new instance of this &#8220;class&#8221;.</p>
<pre lang="javascript">
var myObject = new a('hello world');
var anotherObject = new a('some test');

myObject.print(); // will print the string "hello world"
anotherObject.print(); // will print the string "some test"
</pre>
<p>Thus the function <strong>&#8220;a&#8221;</strong> defined within the code <strong>&#8220;var a = function(name) &#8230;&#8221;</strong> is a class in JavaScript. You can make instances (objects) of this class with the &#8220;new&#8221; operator.</p>
<p>You can use another notation for defining the function &#8220;a&#8221;, so both can be used and it&#8217;s up to you to decide which one is more convenient.</p>
<pre lang="javascript">
function a(name) 
{
	this.name = name;
	
	this.print = function() {
		alert(this.name);	
	}	
}
</pre>
<h2>Prototypes</h2>
<p>JS gives you more power. In most of the languages you&#8217;ve to define the class first and then make objects. In JS you can define a &#8220;class&#8221; then make some objects and then add some properties to the class by using the prototype.</p>
<pre lang="javascript">
var a = function(name) 
{
	this.name = name;
}

var myObj = new a('hello world');

a.prototype.print = function() {
	alert(this.name);	
}

myObj.print();
</pre>
<p>So you can see how you can add functions and properties to an already defined class using the prototype. Thus you can call the &#8220;print&#8221; function on the myObj object.</p>
<h2>Inheritance</h2>
<p>The prototype built-in property can be used to make use of one of the main OOP features &#8211; inheritance. </p>
<pre lang="javascript">
var SuperClass = function()
{
	this.superFunction = function() {
		return 'function in Super Class';	
	}
}

var sup = new SuperClass();
sup.superFunction(); // will return the string "function in Super Class"
</pre>
<p>Now you can add one more class and set its prototype to the SuperClass</p>
<pre lang="javascript">
var SubClass = function()
{
	this.subFunction = function() {
		return 'function in Sub Class';	
	}	
}

SubClass.prototype = new SuperClass();
</pre>
<p>Thus you make SubClass inherit from SuperClass. Now you can call the SuperClass properties from any SubClass object.</p>
<pre lang="javascript">
var sub = new SubClass();
sub.superFunction(); // will return the string "function in Super Class"
sub.subFunction(); // will return the string "function in Sub Class"
</pre>
<p>Even more! You can add properties to the super class with prototype.</p>
<pre lang="javascript">
SuperClass.prototype.myFunc = function() {
	return 'my new function';	
}
</pre>
<p>And then call it from the sub class:</p>
<pre lang="javascript">
sub.myFunc(); // will return the string "my new function"
</pre>
<h2>Override a Function</h2>
<p>What happens if you have the same function name in both classes. Actually this overrides the method in the sub class.</p>
<pre lang="javascript">
var SuperClass = function()
{
	this.myFunc = function() {
		return 'function in Super Class';	
	}
}

var SubClass = function()
{
	this.myFunc = function() {
		return 'function in Sub Class';	
	}	
}

SubClass.prototype = new SuperClass();

var sub = new SubClass();
sub.myFunc(); // will return the string "function in Sub Class"
</pre>
<p>while </p>
<pre lang="javascript">
var sup = new SuperClass();
sup.myFunc(); // will return the string "function in Super Class"
</pre>
<h2>Conclusion</h2>
<p>Now you know there are classes, inheritance and overrides in JavaScript &#8211; thus you can improve your object oriented JavaScript!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/03/02/javascript-inheritance-example/" rel="bookmark" title="JavaScript inheritance example">JavaScript inheritance example </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/05/30/object-oriented-javascript-inheritance/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Returning JSON in a Zend Controller’s Action &#8211; Part 2</title>
		<link>/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/</link>
		<comments>/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 13:39:23 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[elegant solution]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[JSON-RPC]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[Remote procedure call]]></category>
		<category><![CDATA[SOAPjr]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Web services]]></category>

		<guid isPermaLink="false">/?p=1916</guid>
		<description><![CDATA[In a reply from my latest post after following the comments, there is a much elegant solution to this use case. Simply by changing the output with a JSON helper. This also changes the content-type of the returned response. $data = array(...); $this->_helper->json($data);<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/08/13/returning-json-in-a-zend-controllers-action/" rel="bookmark" title="Returning JSON in a Zend Controller&#8217;s Action">Returning JSON in a Zend Controller&#8217;s Action </a></li>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/06/23/bind-zend-action-with-non-default-view-part-2/" rel="bookmark" title="Bind Zend Action with Non-Default View &#8211; Part 2">Bind Zend Action with Non-Default View &#8211; Part 2 </a></li>
<li><a href="/2010/06/24/zend-framework-inject-javascript-code-in-a-actionview/" rel="bookmark" title="Zend Framework: Inject JavaScript Code in a Action/View">Zend Framework: Inject JavaScript Code in a Action/View </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>In a reply from my latest post after following the comments, there is a much elegant solution to this use case. Simply by changing the output with a JSON helper. This also changes the content-type of the returned response.</p>
<pre lang="php">
$data = array(...);
$this->_helper->json($data);
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/08/13/returning-json-in-a-zend-controllers-action/" rel="bookmark" title="Returning JSON in a Zend Controller&#8217;s Action">Returning JSON in a Zend Controller&#8217;s Action </a></li>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/06/23/bind-zend-action-with-non-default-view-part-2/" rel="bookmark" title="Bind Zend Action with Non-Default View &#8211; Part 2">Bind Zend Action with Non-Default View &#8211; Part 2 </a></li>
<li><a href="/2010/06/24/zend-framework-inject-javascript-code-in-a-actionview/" rel="bookmark" title="Zend Framework: Inject JavaScript Code in a Action/View">Zend Framework: Inject JavaScript Code in a Action/View </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Returning JSON in a Zend Controller&#8217;s Action</title>
		<link>/2010/08/13/returning-json-in-a-zend-controllers-action/</link>
		<comments>/2010/08/13/returning-json-in-a-zend-controllers-action/#comments</comments>
		<pubDate>Fri, 13 Aug 2010 13:14:26 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[clear solution]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[encode()]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[JSON-RPC]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[zend_json]]></category>

		<guid isPermaLink="false">/?p=1905</guid>
		<description><![CDATA[There are three basic ways that you can achieve that. First of all what&#8217;s the task? You&#8217;ve an array, either from a database result or whatever, and you encode it JSON with Zend_Json::encode($array) // IndexController.php class IndexController extends Zend_Controller_Action { public function indexAction() { $data = array(...); $this->view->data = Zend_Json::encode($data); } } The result in &#8230; <a href="/2010/08/13/returning-json-in-a-zend-controllers-action/" class="more-link">Continue reading <span class="screen-reader-text">Returning JSON in a Zend Controller&#8217;s Action</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/" rel="bookmark" title="Returning JSON in a Zend Controller’s Action &#8211; Part 2">Returning JSON in a Zend Controller’s Action &#8211; Part 2 </a></li>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/06/07/bind-zend-action-with-non-default-view/" rel="bookmark" title="Bind Zend Action with Non-Default View">Bind Zend Action with Non-Default View </a></li>
<li><a href="/2010/06/24/zend-framework-inject-javascript-code-in-a-actionview/" rel="bookmark" title="Zend Framework: Inject JavaScript Code in a Action/View">Zend Framework: Inject JavaScript Code in a Action/View </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>There are three basic ways that you can achieve that. First of all what&#8217;s the task? You&#8217;ve an array, either from a database result or whatever, and you encode it JSON with Zend_Json::encode($array)</p>
<pre lang="php">
// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
		
		$this->view->data = Zend_Json::encode($data);	
	}	
}
</pre>
<p>The result in general is a specially formatted string. So you can simply set it up to a view member variable and pass it to the view.</p>
<pre lang="php">
// index/index.phtml
echo $this->data
</pre>
<p>In that case you&#8217;ve a .phtml file to maintain, so lets just return the string and &#8220;setNoRender&#8221; the view in our second try.</p>
<pre lang="php">
// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
		
		echo Zend_Json::encode($data);	
		
		$this->_helper->viewRenderer->setNoRender(true);
	}	
}
</pre>
<p>Actually this is pretty much the most clear solution, but actually you can output the JSON string and simply exit() as it&#8217;s shown in our third example.</p>
<pre lang="php">
// IndexController.php
class IndexController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$data = array(...);
		
		echo Zend_Json::encode($data);	
		
		exit();
	}	
}
</pre>
<p>Which one is to be used is up to the developer&#8217;s choice, mine is the third one as it&#8217;s the minimal one.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/08/19/returning-json-in-a-zend-controller%e2%80%99s-action-part-2/" rel="bookmark" title="Returning JSON in a Zend Controller’s Action &#8211; Part 2">Returning JSON in a Zend Controller’s Action &#8211; Part 2 </a></li>
<li><a href="/2010/06/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
<li><a href="/2010/06/07/bind-zend-action-with-non-default-view/" rel="bookmark" title="Bind Zend Action with Non-Default View">Bind Zend Action with Non-Default View </a></li>
<li><a href="/2010/06/24/zend-framework-inject-javascript-code-in-a-actionview/" rel="bookmark" title="Zend Framework: Inject JavaScript Code in a Action/View">Zend Framework: Inject JavaScript Code in a Action/View </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/08/13/returning-json-in-a-zend-controllers-action/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Quick Look at JavaScript Objects</title>
		<link>/2010/08/11/quick-look-at-javascript-objects/</link>
		<comments>/2010/08/11/quick-look-at-javascript-objects/#respond</comments>
		<pubDate>Wed, 11 Aug 2010 17:38:55 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[C++ classes]]></category>
		<category><![CDATA[Class]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Function]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JavaScript syntax]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Set-builder notation]]></category>
		<category><![CDATA[Software engineering]]></category>

		<guid isPermaLink="false">/?p=1900</guid>
		<description><![CDATA[JavaScript Objects As you may know there are different notations of objects in JavaScript, and there are slight differences. However here I&#8217;m gonna achieve the same thing with different notations. The first one is the object notation in JavaScript known mostly from JSON. There you&#8217;ve to construct a key/value pairs, divided by a colon: var &#8230; <a href="/2010/08/11/quick-look-at-javascript-objects/" class="more-link">Continue reading <span class="screen-reader-text">Quick Look at JavaScript Objects</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2010/05/24/javascript-objects-coding-style/" rel="bookmark" title="JavaScript Objects Coding Style">JavaScript Objects Coding Style </a></li>
<li><a href="/2009/07/08/javascript-closures-in-brief/" rel="bookmark" title="JavaScript closures in brief">JavaScript closures in brief </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>JavaScript Objects</h2>
<p>As you may know there are different notations of objects in JavaScript, and there are slight differences. However here I&#8217;m gonna achieve the same thing with different notations. The first one is the object notation in JavaScript known mostly from JSON. There you&#8217;ve to construct a key/value pairs, divided by a colon:</p>
<pre lang="javascript">
var class1 = {
    a : 0,
    func1 : function() {
        console.log(class1.a);
    },
    func2 : function(a) {
        this.a = a;
    }
}
class1.func2(3);
</pre>
<p>Here we have two functions &#8211; func1 and func2 and one member variable. Func2 is setting up the member variable, it&#8217;s something like a setter in some languages like Java and PHP, and the func1 is printing the value of that variable via console.log(). Note that in the body of func1() the variable &#8220;a&#8221; is accessed with the class name: class1.a. Here the notation can be changed to this.a, which will result in the same thing.</p>
<pre lang="javascript">
...
console.log(this.a);
...
</pre>
<h2>Notation #2</h2>
<p>While in the notation I&#8217;ve just used is not possible to have two different instances from the same class, in the next example this is possible. In JavaScript the objects are even the functions, and you can access the function&#8217;s private variables with the dot notation.</p>
<pre lang="javascript">
var class2 = function() {
    this.a = 0;
    this.func1 = function() {
        console.log(this.a);
    }

    this.func2 = function(a) {
        this.a = a;
    }
}
</pre>
<p>To use this object you&#8217;ve to use the &#8220;new&#8221; operator.</p>
<pre lang="javascript">
var c = new class2();
c.func2(4);
</pre>
<p>This helps you create more than one instance of the same class.</p>
<pre lang="javascript">
var c = new class2();
var d = new class2();
c.func2(3);
d.func2(4);
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2010/05/24/javascript-objects-coding-style/" rel="bookmark" title="JavaScript Objects Coding Style">JavaScript Objects Coding Style </a></li>
<li><a href="/2009/07/08/javascript-closures-in-brief/" rel="bookmark" title="JavaScript closures in brief">JavaScript closures in brief </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/08/11/quick-look-at-javascript-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New Name for AJAX</title>
		<link>/2010/04/27/new-name-for-ajax/</link>
		<comments>/2010/04/27/new-name-for-ajax/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 16:14:28 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[web development]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">/?p=1493</guid>
		<description><![CDATA[Should it be called AJAJ since there&#8217;s more JSON instead of XML?!<div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2009/11/03/ajax-datatypes-in-jquery-format-and-access/" rel="bookmark" title="AJAX dataTypes in jQuery. Format and access.">AJAX dataTypes in jQuery. Format and access. </a></li>
<li><a href="/2009/03/19/jquery-ajax-script-call/" rel="bookmark" title="JQuery ajax script call">JQuery ajax script call </a></li>
<li><a href="/2011/10/10/php-does-simplexmlelement-have-tostring-method-no-better-use-asxml/" rel="bookmark" title="PHP: Does SimpleXMLElement have toString() method? No, better use asXML()!">PHP: Does SimpleXMLElement have toString() method? No, better use asXML()! </a></li>
<li><a href="/2009/11/02/ajax-in-jquery/" rel="bookmark" title="$.ajax in jQuery">$.ajax in jQuery </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Should it be called AJAJ since there&#8217;s more JSON instead of XML?!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2009/11/03/ajax-datatypes-in-jquery-format-and-access/" rel="bookmark" title="AJAX dataTypes in jQuery. Format and access.">AJAX dataTypes in jQuery. Format and access. </a></li>
<li><a href="/2009/03/19/jquery-ajax-script-call/" rel="bookmark" title="JQuery ajax script call">JQuery ajax script call </a></li>
<li><a href="/2011/10/10/php-does-simplexmlelement-have-tostring-method-no-better-use-asxml/" rel="bookmark" title="PHP: Does SimpleXMLElement have toString() method? No, better use asXML()!">PHP: Does SimpleXMLElement have toString() method? No, better use asXML()! </a></li>
<li><a href="/2009/11/02/ajax-in-jquery/" rel="bookmark" title="$.ajax in jQuery">$.ajax in jQuery </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/04/27/new-name-for-ajax/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>jQuery localStorage plugin (alpha)</title>
		<link>/2010/02/26/jquery-localstorage-plugin-alpha/</link>
		<comments>/2010/02/26/jquery-localstorage-plugin-alpha/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 07:20:04 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[localStorage]]></category>

		<guid isPermaLink="false">/?p=1150</guid>
		<description><![CDATA[After submitting the HTML5 localStorage wrap plugin for jQuery, there comes the new version, hopefully more stable and reliable! (function(jQuery) { var supported = true; if (typeof localStorage == 'undefined' &#124;&#124; typeof JSON == 'undefined') supported = false; else var ls = localStorage; this.setItem = function(key, value, lifetime) { if (!supported) return false; if (typeof &#8230; <a href="/2010/02/26/jquery-localstorage-plugin-alpha/" class="more-link">Continue reading <span class="screen-reader-text">jQuery localStorage plugin (alpha)</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/02/25/jquery-localstorage-plugin/" rel="bookmark" title="jQuery localStorage plugin">jQuery localStorage plugin </a></li>
<li><a href="/2010/02/24/storing-javascript-objects-in-html5-localstorage/" rel="bookmark" title="Storing JavaScript objects in html5 localStorage">Storing JavaScript objects in html5 localStorage </a></li>
<li><a href="/2010/02/17/clickoutside-jquery-plugin/" rel="bookmark" title="clickoutside jQuery plugin">clickoutside jQuery plugin </a></li>
<li><a href="/2010/02/01/writing-a-jquery-plugin-part-2-sample-plugin/" rel="bookmark" title="Writing a jQuery plugin &#8211; (part 2). Sample plugin.">Writing a jQuery plugin &#8211; (part 2). Sample plugin. </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>After submitting the HTML5 localStorage wrap plugin for jQuery, there comes the new version, hopefully more stable and reliable!</p>
<pre lang="javascript" line="1">
(function(jQuery) {

   var supported = true;
   if (typeof localStorage == 'undefined' || typeof JSON == 'undefined')
      supported = false;
   else
      var ls = localStorage;

   this.setItem = function(key, value, lifetime) {
      if (!supported)
         return false;

      if (typeof lifetime == 'undefined')
         lifetime = 60000;

      ls.setItem(key, JSON.stringify(value));
      var time = new Date();
      ls.setItem('meta_ct_'+key, time.getTime());
      ls.setItem('meta_lt_'+key, lifetime);
   };

   this.getItem = function(key) {
      if (!supported)
         return false;

      var time = new Date();
      if (time.getTime() - ls.getItem('meta_ct_'+key) &gt; ls.getItem('meta_lt_'+key)) {
         ls.removeItem(key);
         ls.removeItem('meta_ct_'+key);
         ls.removeItem('meta_lt_'+key);
         return false;
      }
      return JSON.parse(ls.getItem(key));
   };

   this.removeItem = function(key) {
      if (!supported)
         return false;

      ls.removeItem(key);
      ls.removeItem('meta_ct_'+key);
      ls.removeItem('meta_lt_'+key);
      return true;
   };

   jQuery.localStorage = this;

})(jQuery);

if (!$.localStorage.getItem('test')) {
   $.localStorage.setItem('test', ['stoimen'], 5000);
   console.log('dynamic');
} else {
   console.log('from cache');
}</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/02/25/jquery-localstorage-plugin/" rel="bookmark" title="jQuery localStorage plugin">jQuery localStorage plugin </a></li>
<li><a href="/2010/02/24/storing-javascript-objects-in-html5-localstorage/" rel="bookmark" title="Storing JavaScript objects in html5 localStorage">Storing JavaScript objects in html5 localStorage </a></li>
<li><a href="/2010/02/17/clickoutside-jquery-plugin/" rel="bookmark" title="clickoutside jQuery plugin">clickoutside jQuery plugin </a></li>
<li><a href="/2010/02/01/writing-a-jquery-plugin-part-2-sample-plugin/" rel="bookmark" title="Writing a jQuery plugin &#8211; (part 2). Sample plugin.">Writing a jQuery plugin &#8211; (part 2). Sample plugin. </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/02/26/jquery-localstorage-plugin-alpha/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Storing JavaScript objects in html5 localStorage</title>
		<link>/2010/02/24/storing-javascript-objects-in-html5-localstorage/</link>
		<comments>/2010/02/24/storing-javascript-objects-in-html5-localstorage/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 15:39:31 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Cloud standards]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Google Chrome]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Markup languages]]></category>
		<category><![CDATA[Mozilla Firefox]]></category>
		<category><![CDATA[Mozilla Firefox 3.5]]></category>
		<category><![CDATA[Technology/Internet]]></category>

		<guid isPermaLink="false">/?p=1138</guid>
		<description><![CDATA[There is a rising new age of HTML5, which comes with very nice features as video tag and localStorage. What localStorage is? In fact we have been waiting for long time to have something that give us the power of storing more and more on the client side. That&#8217;s because the net is becoming larger &#8230; <a href="/2010/02/24/storing-javascript-objects-in-html5-localstorage/" class="more-link">Continue reading <span class="screen-reader-text">Storing JavaScript objects in html5 localStorage</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/02/25/jquery-localstorage-plugin/" rel="bookmark" title="jQuery localStorage plugin">jQuery localStorage plugin </a></li>
<li><a href="/2010/02/26/jquery-localstorage-plugin-alpha/" rel="bookmark" title="jQuery localStorage plugin (alpha)">jQuery localStorage plugin (alpha) </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/04/13/secure-localstorage-now-thats-a-good-question/" rel="bookmark" title="Secure localStorage? Now that&#8217;s a good question!">Secure localStorage? Now that&#8217;s a good question! </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>There is a rising new age of HTML5, which comes with very nice features as video tag and localStorage. What localStorage is? In fact we have been waiting for long time to have something that give us the power of storing more and more on the client side. That&#8217;s because the net is becoming larger and therefore heavy.</p>
<p>Imagine if you have the possibility to store large JSON returned from an AJAX call on the client. That&#8217;s now reality with the localStorage object in HTML5 and it can be accessed with something like this code:</p>
<pre lang="javascript">localStorage.setItem(key, value);
alert(localStorage.getItem(key));
</pre>
<h2>Can we store entire objects?</h2>
<p>Yes there is a way extending a bit the logic of the code above. The localStorage in fact stores only strings, but what about arrays and objects. You can additionally use JSON global objects and its two methods &#8211; stringify and parse:</p>
<pre lang="javascript">var a = JSON.stringify({name:'obj'});
alert(JSON.parse(a));
</pre>
<h2>Do browsers support all that?</h2>
<p>Of course &#8230; not! localStorage is supported by Firefox 3.5+, Chrome 2+, Safari 4+ and MSIE 8+. The solution is not to rely on browser version, but to check for object existence, and than to combine both techniques:</p>
<pre lang="javascript">localStorage.setItem('a', JSON.stringify({ name : 'obj' }));
alert(JSON.parse(localStorage.getItem('a')));
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/02/25/jquery-localstorage-plugin/" rel="bookmark" title="jQuery localStorage plugin">jQuery localStorage plugin </a></li>
<li><a href="/2010/02/26/jquery-localstorage-plugin-alpha/" rel="bookmark" title="jQuery localStorage plugin (alpha)">jQuery localStorage plugin (alpha) </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/04/13/secure-localstorage-now-thats-a-good-question/" rel="bookmark" title="Secure localStorage? Now that&#8217;s a good question!">Secure localStorage? Now that&#8217;s a good question! </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/02/24/storing-javascript-objects-in-html5-localstorage/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
