<?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>Chris West&#039;s Blog</title>
	<atom:link href="http://cwestblog.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://cwestblog.com</link>
	<description>Programming, math, and more.</description>
	<lastBuildDate>Tue, 21 May 2013 18:10:39 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>JavaScript &#8211; Modify URL Parameters</title>
		<link>http://cwestblog.com/2013/05/21/javascript-modify-url-parameters/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-modify-url-parameters</link>
		<comments>http://cwestblog.com/2013/05/21/javascript-modify-url-parameters/#comments</comments>
		<pubDate>Tue, 21 May 2013 18:10:39 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JScript]]></category>
		<category><![CDATA[Function]]></category>
		<category><![CDATA[Regular Expressions]]></category>

		<guid isPermaLink="false">http://cwestblog.com/?p=1788</guid>
		<description><![CDATA[Recently I had to develop a solution which involved changing the HREF attributes of links in the navigation bar of a site. This had to be done on the JavaScript side because at my company we are the 3rd-party JavaScript &#8230; <a href="http://cwestblog.com/2013/05/21/javascript-modify-url-parameters/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Recently I had to develop a solution which involved changing the HREF attributes of links in the navigation bar of a site.  This had to be done on the JavaScript side because at my company we are the 3rd-party JavaScript solution for modifying other companies&#8217; sites.  That being said, I came up with one solution because the URL parameter was always the same but I figured I would publicly release the code for doing this in such a way that you can modify the value of any URL parameter:</p>
<pre class="brush: jscript; title: ; notranslate">
/**
 * @license Copyright 2013 - Chris West - MIT Licensed
 */
(function(expCharsToEscape, expEscapedSpace, expNoStart, undefined) {
  /**
   * Modifies the given URL, returning it with the given parameter
   * changed to the given value.  The parameter is added if it didn't
   * already exist.  The parameter is removed if null or undefined is
   * specified as the value.
   * @param {string} url  The URL to be modified.
   * @param {string} paramName  The URL parameter whose value will be
   *     modified.
   * @param {string} paramValue  The value to assign.  This will be
   *     escaped using encodeURIComponent.
   * @return {string}  The updated URL.
   */
  modURLParam = function(url, paramName, paramValue) {
    paramValue = paramValue != undefined
      ? encodeURIComponent(paramValue).replace(expEscapedSpace, '+')
      : paramValue;
    var pattern = new RegExp(
      '([?&amp;]'
      + paramName.replace(expCharsToEscape, '\\$1')
      + '=)[^&amp;]*'
    );
    if(pattern.test(url)) {
      return url.replace(
        pattern,
        function($0, $1) {
          return paramValue != undefined ? $1 + paramValue : ''; 
        }
      ).replace(expNoStart, '$1?');
    }
    else if (paramValue != undefined) {
      return url + (url.indexOf('?') + 1 ? '&amp;' : '?')
        + paramName + '=' + paramValue;
    }
    else {
      return url;
    }
  };
})(/([\\\/\[\]{}().*+?|^$])/g, /%20/g, /^([^?]+)&amp;/);
</pre>
<p>The following are some example calls to this function:</p>
<pre class="brush: jscript; title: ; notranslate">
// Initial URL
var url = 'http://example.com/';
alert(url);

// http://example.com/?q=search+term
url = modURLParam(url, 'q', 'search term');
alert(url);

// http://example.com/?q=search+term&amp;name=Guillermo
url = modURLParam(url, 'name', 'Guillermo');
alert(url);

// http://example.com/?q=search+term+2&amp;name=Guillermo
url = modURLParam(url, 'q', 'search term 2');
alert(url);

// http://example.com/?name=Guillermo
url = modURLParam(url, 'q');
alert(url);

// http://example.com/?name=Guillermo&amp;q=termino
url = modURLParam(url, 'q', 'termino');
alert(url);

// http://example.com/?name=Guillermo
url = modURLParam(url, 'q', null);
alert(url);
</pre>
<p>Feel free to re-use the code! <img src='http://cwestblog.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/05/21/javascript-modify-url-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript &#8211; Substitution Groups &amp; Functions</title>
		<link>http://cwestblog.com/2013/05/02/javascript-substitution-groups-and-functions/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-substitution-groups-and-functions</link>
		<comments>http://cwestblog.com/2013/05/02/javascript-substitution-groups-and-functions/#comments</comments>
		<pubDate>Thu, 02 May 2013 17:16:57 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JScript]]></category>
		<category><![CDATA[Function]]></category>
		<category><![CDATA[Regular Expressions]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://gotochriswest.com/blog/?p=1766</guid>
		<description><![CDATA[One of the things that I often end up doing is using JavaScript&#8217;s replace function with a regular expression and a callback function. Recently, though, I have been thinking about redeveloping an HTML application (HTA) that I made a long &#8230; <a href="http://cwestblog.com/2013/05/02/javascript-substitution-groups-and-functions/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>One of the things that I often end up doing is using JavaScript&#8217;s replace function with a regular expression and a callback function.  Recently, though, I have been thinking about redeveloping an HTML application (HTA) that I made a long time ago for PCs.  This HTA gave me the ability to write regular expressions and replacement strings which could alter the matched groups in ways that normal string substitution doesn&#8217;t allow without using callback functions.  Let&#8217;s take the following file names as examples:</p>
<ul>
<li>001-the-nephews-come-to-town.mpg</li>
<li>002-scroogey-scroogers.mp4</li>
<li>32-hewi&#8217;s-lost-pet.mp4</li>
<li>109-copped-by-the-coppers.mpeg</li>
</ul>
<p>The file renamer that I use to have would allow these files to be renamed as the following by using <code>/^(d+)(.+)(?=.w+$)/</code> as the regular expression and <code>"Episode ${1,RLZ} -${2,D2S,PROPER}"</code> as the replacement:</p>
<ul>
<li>Episode 1 &#8211; The Nephews Come To Town.mpg</li>
<li>Episode 2 &#8211; Scroogey Scroogers.mp4</li>
<li>Episode 32 &#8211; Hewi&#8217;s Lost Pet.mp4</li>
<li>Episode 109 &#8211; Copped By The Coppers.mpeg</li>
</ul>
<p>As the first step towards achieving my goal, I wrote the following <code>sub</code> function which can accomplish this:</p>
<pre class="brush: jscript; title: ; notranslate">
(function() {
  var functions = {};
  var hasOwnProperty = functions.hasOwnProperty;
  this.sub = function(subject, reTarget, strReplacement, objFns) {
    if(!reTarget &amp;&amp; !strReplacement &amp;&amp; !objFns) {
      for(var key in subject) {
        if(hasOwnProperty.call(subject, key)) {
          functions[key] = subject[key];
        }
      }
    }
    else {
      return subject.replace(reTarget, function(match) {
        var args = arguments;
        var reGroups = [];
        var i = args.length - 2;
        while(--i &gt; 0) {
          reGroups.push(i);
        }
        reGroups = '(' + reGroups.join('|') + ')';
        reGroups = new RegExp('\$(?:' + reGroups + '|\{' + reGroups + '((?:,\w+)*)\})', 'g');
        return strReplacement.replace(reGroups, function(match, index, index2, fnsToUse) {
          fnsToUse = fnsToUse ? fnsToUse.slice(1).split(',') : [];
          var ret = args[index || index2];
          for(var i = 0, len = fnsToUse.length; i &lt; len; i++) {
            var fnName = fnsToUse[i];
            var fn;
            if((objFns &amp;&amp; hasOwnProperty.call(objFns, fnName) &amp;&amp; (fn = objFns[fnName]))
                || (hasOwnProperty.call(functions, fnName) &amp;&amp; (fn = functions[fnName]))) {
              ret = fn(ret, args);
            }
          }
          return ret;
        });
      });
    }
  };
})();
</pre>
<p>This function actually acts differently depending on the parameters that are supplied.  The first way in which the function can be called is with four parameters:</p>
<ol>
<li><b>subject</b> &#8211; string:<br />The string that is to be modified.</li>
<li><b>reTarget</b> &#8211; RegExp:<br />The regular expression used to capture substrings.</li>
<li><b>strReplacement</b> &#8211; string:<br />The replacement string which can have the normal captured group expressions (eg. $1, $3, etc.), the new type of captured group expressions (eg. ${1}, ${3,RLZ}, etc.) and/or normal substrings.</li>
<li><b>objFns</b> &#8211; Object:<br />Optional object whose keys correspond to functions referenced in the new type of group expressions.  Each value should be a function where the first parameter passed to it will be the matched group and the second will be the arguments object which is normally passed to the callback function.  The functions should return the string replacement for the captured group expression.</li>
</ol>
<pre class="brush: jscript; title: ; notranslate">
var filename = sub(
  &quot;023-we-are-the-tigers.jpg&quot;,
  /^(d+)(.+)(?=.w+$)/,
  &quot;Episode ${1,RLZ} -${2,D2S,PROPER}&quot;,
  {
    RLZ: function(match) {
      return match.replace(/^0+(?!$)/, '');
    },
    D2S: function(match) {
      return match.replace(/-/g, ' ');
    },
    PROPER: function(match) {
      return match.toProperCase();
    },
    UPPER: function(match) {
      return match.toUpperCase();
    },
    CHARCODE: function(match) {
      return '&lt;' + match + '=' + match.charCodeAt(0) + '&gt;';
    }
  }
);
alert(filename);  // &quot;Episode 23 - We Are The Tigers.jpg&quot;

var str = sub(
  &quot;abcdefghijklmnopqrstuvwxyz&quot;,
  /([aeiou])/g,
  &quot;&lt;${1,UPPER}&gt;&quot;,
  {
    UPPER: function(match) {
      return match.toUpperCase();
    }
  }
);
alert(str);  // &quot;&lt;A&gt;bcd&lt;E&gt;fgh&lt;I&gt;jklmn&lt;O&gt;pqrst&lt;U&gt;vwxyz&quot; 
</pre>
<p>The reason the fourth parameter is optional is because those captured group expression replacement functions could be predefined for all calls to this <code>sub</code> function.  If the function is just called with one parameter, that parameter should be the same as the fourth parameter outlined previously.  The captured group expression replacement functions will remain persistent for the remainder of the page/program session:</p>
<pre class="brush: jscript; title: ; notranslate">
sub({
  RLZ: function(match) {
    return match.replace(/^0+(?!$)/, '');
  },
  D2S: function(match) {
    return match.replace(/-/g, ' ');
  },
  PROPER: function(match) {
    return match.toProperCase();
  }
});
var filenames = [
  &quot;001-the-nephews-come-to-town.mpg&quot;,
  &quot;002-scroogey-scroogers.mp4&quot;,
  &quot;32-hewi's-lost-pet.mp4&quot;,
  &quot;109-copped-by-the-coppers.mpeg&quot;
];
var exp = /^(d+)(.+)(?=.w+$)/;
var replacement = &quot;Episode ${1,RLZ} -${2,D2S,PROPER}&quot;;
for(var i = 0; i &lt; filenames.length; i++) {
  filenames[i] = sub(filenames[i], exp, replacement);
}
alert(filenames.join('n'));
</pre>
<p>The above code will result in the following filenames:</p>
<pre class="brush: plain; title: ; notranslate">
Episode 1 - The Nephews Come To Town.mpg
Episode 2 - Scroogey Scroogers.mp4
Episode 32 - Hewi's Lost Pet.mp4
Episode 109 - Copped By The Coppers.mpeg
</pre>
<p>Well, now that I have this code out of the way, hopefully the next step will be to actually make the File Renamer.  When I do finish creating it, you can be sure to find it on this blog.  <img src='http://cwestblog.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/05/02/javascript-substitution-groups-and-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JScript &#8211; File &amp; Folder Chomper</title>
		<link>http://cwestblog.com/2013/04/19/jscript-file-an-folder-chomper/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jscript-file-an-folder-chomper</link>
		<comments>http://cwestblog.com/2013/04/19/jscript-file-an-folder-chomper/#comments</comments>
		<pubDate>Sat, 20 Apr 2013 01:06:02 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JScript]]></category>
		<category><![CDATA[WScript]]></category>

		<guid isPermaLink="false">http://gotochriswest.com/blog/?p=1749</guid>
		<description><![CDATA[I use to always work on Windows and at times it seemed that certain files just didn&#8217;t want to go to the recycling bin. For that reason I would always write a JScript which had the following code: When a &#8230; <a href="http://cwestblog.com/2013/04/19/jscript-file-an-folder-chomper/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I use to always work on Windows and at times it seemed that certain files just didn&#8217;t want to go to the recycling bin.  For that reason I would always write a JScript which had the following code:</p>
<pre class="brush: jscript; title: ; notranslate">
(new ActiveXObject(&quot;Scripting.FileSystemObject&quot;).DeleteFile(WScript.Arguments.Item(0))
</pre>
<p>When a file was dragged onto that script, the file would be de-referenced (deleted permanently).  A friend recently called me and asked for a similar solution so I decided to post it for everyone:<br />
<a href="http://cwestblog.com/wp-content/uploads/2013/04/File-Folder-Chomper.js" style="font-family: 'Trebuchet MS', Verdana, sans-serif; line-height: 1em; color: #3d64ff; font-weight:bold; font-size: 24px; text-shadow:0px 0px 0 rgb(-24,15,170),1px 1px 0 rgb(-109,-70,85),2px 2px 0 rgb(-194,-155,0), 3px 3px 0 rgb(-279,-240,-85),4px 4px 3px rgba(0,0,0,0.45),4px 4px 1px rgba(0,0,0,0.5),0px 0px 3px rgba(0,0,0,.2);">Download the File &#038; Folder Chomper</a></p>
<p>The above script works the same way (on Windows only):  drag the files and folders onto the script&#8217;s icon in order to have all of the permanently deleted.  Have fun!!!</p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/04/19/jscript-file-an-folder-chomper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Batch Excel To CSV Converter Application</title>
		<link>http://cwestblog.com/2013/04/12/batch-excel-to-csv-converter-application/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=batch-excel-to-csv-converter-application</link>
		<comments>http://cwestblog.com/2013/04/12/batch-excel-to-csv-converter-application/#comments</comments>
		<pubDate>Fri, 12 Apr 2013 07:23:17 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[HTA]]></category>
		<category><![CDATA[Excel]]></category>

		<guid isPermaLink="false">http://gotochriswest.com/blog/?p=1737</guid>
		<description><![CDATA[I have been truly fascinated by the amount of visitors that I get because of the simple XLS/XLSX to CSV converter script that I made a while back (original post). For that reason I have created an HTML application (HTA) &#8230; <a href="http://cwestblog.com/2013/04/12/batch-excel-to-csv-converter-application/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I have been truly fascinated by the amount of visitors that I get because of the simple XLS/XLSX to CSV converter script that I made a while back (<a href="http://gotochriswest.com/blog/2011/05/05/excel-batch-convert-xls-to-csv/" title="Excel – Batch Convert XLS To CSV" target="_blank">original post</a>).  For that reason I have created an HTML application (HTA) which offers the same functionality and then some:<br />
<a href="http://cwestblog.com/wp-content/uploads/2013/04/XLS-to-CSV-Converter.zip" style="font-family: 'Trebuchet MS', 'Bookman Old Style', serif; line-height: 1em; color: #2757e6; font-weight:bold; font-size: 40px; text-shadow:0px 0px 0 rgb(-25,23,166),1px 1px 0 rgb(-88,-40,103),2px 2px 0 rgb(-152,-104,39),3px 3px 0 rgb(-216,-168,-25), 4px 4px 0 rgb(-280,-232,-89),5px 5px 4px rgba(0,0,0,1),5px 5px 1px rgba(0,0,0,0.5),0px 0px 4px rgba(0,0,0,.2);"><img src="http://cwestblog.com/wp-content/uploads/2013/04/XLS-To-CSV-Converter.png" alt="XLS To CSV Converter" width="1000" height="724" class="alignnone size-full wp-image-1738" /><br />
DOWNLOAD THIS APP</a></p>
<h2>How this Differs from the Script</h2>
<ul>
<li>There is an easy to use interface.</li>
<li>You can customize how the resulting files are named.</li>
<li>You can filter which sheets will be exported as CSVs using simple text matches and/or regular expressions.</li>
<li>You will see the results of the conversion process in one place after the process is finished.</li>
</ul>
<h2>Using It</h2>
<ul>
<li>Download it from <a href="http://cwestblog.com/wp-content/uploads/2013/04/XLS-to-CSV-Converter.zip">here</a>.</li>
<li>Unzip the .HTA file.</li>
<li>Double-click on the .HTA file.</li>
<li>Click the <b>Browse for Folder</b> button and browse for the folder that contains the XLS and/or XLSX files whose worksheets should be exported as CSVs.</li>
<li>Modify the <b>CSV Naming Schema</b> as you like (hints are given in the application).</li>
<li>If you would like to only export worksheets with specific names, enter those names in the <b>Sheet Filters</b> textbox (only one per line).  You may also use JavaScript-style regular expressions (one on each line) to match the sheets that you want to convert.</li>
<li>If you would like to remove the linefeed characters from all cells, check the appropriate checkbox.</li>
<li>Click the <b>Start Conversion</b> button and wait for the results to appear.</li>
</ul>
<h2>Plans for Improvement</h2>
<p>As of right now this application is very simple, but I do hope to beef it up a little as time goes on.  Let me know if you have any comments, questions, suggestions, or issues with this new application.  Most of all, have fun!!! <img src='http://cwestblog.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/04/12/batch-excel-to-csv-converter-application/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript &#8211; Get Window Size</title>
		<link>http://cwestblog.com/2013/04/11/javascript-get-window-size/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-get-window-size</link>
		<comments>http://cwestblog.com/2013/04/11/javascript-get-window-size/#comments</comments>
		<pubDate>Thu, 11 Apr 2013 04:00:03 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Function]]></category>

		<guid isPermaLink="false">http://gotochriswest.com/blog/?p=1735</guid>
		<description><![CDATA[At times you may want to get the size of the window. I don&#8217;t remember where I came across the original code, but I modified it and created the following function: As far as I can tell, this should work &#8230; <a href="http://cwestblog.com/2013/04/11/javascript-get-window-size/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>At times you may want to get the size of the window.  I don&#8217;t remember where I came across the original code, but I modified it and created the following function:</p>
<pre class="brush: jscript; title: ; notranslate">
function getWindowSize() {
  var doc = document,
    body = doc.body,
    docElem = doc.documentElement,
    docElemHeight = docElem.clientHeight,
    docElemWidth = docElem.clientWidth,
    css1Compat = doc.compatMode === 'CSS1Compat';
  return {
    height: css1Compat &amp;&amp; docElemHeight || body &amp;&amp; body.clientHeight || docElemHeight,
    width: css1Compat &amp;&amp; docElemWidth || body &amp;&amp; body.clientWidth || docElemWidth
  };
}
</pre>
<p>As far as I can tell, this should work in all browsers, but if you find that it doesn&#8217;t at times, please let me know.  <img src='http://cwestblog.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/04/11/javascript-get-window-size/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript &#8211; Comparing &amp; Sorting Strings with Numbers</title>
		<link>http://cwestblog.com/2013/04/10/javascript-comparing-and-sorting-strings-with-numbers/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-comparing-and-sorting-strings-with-numbers</link>
		<comments>http://cwestblog.com/2013/04/10/javascript-comparing-and-sorting-strings-with-numbers/#comments</comments>
		<pubDate>Wed, 10 Apr 2013 16:45:56 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JScript]]></category>
		<category><![CDATA[Array]]></category>
		<category><![CDATA[Function]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">http://gotochriswest.com/blog/?p=1712</guid>
		<description><![CDATA[Well before I had this site, I created a program which needed to order file names such as the following: Unfortunately, if you just use the normal {Array}.sort() without a callback function, the following will be the resulting order of &#8230; <a href="http://cwestblog.com/2013/04/10/javascript-comparing-and-sorting-strings-with-numbers/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Well before I had this site, I created a program which needed to order file names such as the following:</p>
<pre class="brush: plain; title: ; notranslate">
Episode 20 - There's More Than One of Everything.mp4
Episode 4 - The Arrival.mp4
Episode 7 - In Which We Meet Mr. Jones.mp4
Episode 15 - Inner Child.mp4
Episode 6 - The Cure.mp4
Episode 3 - The Ghost Network.mp4
</pre>
<p>Unfortunately, if you just use the normal <code><i>{Array}</i>.sort()</code> without a callback function, the following will be the resulting order of the file names:</p>
<pre class="brush: plain; title: ; notranslate">
Episode 15 - Inner Child.mp4
Episode 20 - There's More Than One of Everything.mp4
Episode 3 - The Ghost Network.mp4
Episode 4 - The Arrival.mp4
Episode 6 - The Cure.mp4
Episode 7 - In Which We Meet Mr. Jones.mp4
</pre>
<p>As you can see, the 15th episode comes before the 3rd episode after being sorted but in most cases we would want the order to be as follows:</p>
<pre class="brush: plain; title: ; notranslate">
Episode 3 - The Ghost Network.mp4
Episode 4 - The Arrival.mp4
Episode 6 - The Cure.mp4
Episode 7 - In Which We Meet Mr. Jones.mp4
Episode 15 - Inner Child.mp4
Episode 20 - There's More Than One of Everything.mp4
</pre>
<p>For this reason, I wrote the <code>cmpStringsWithNumbers</code> function which takes two strings and compares them by separating the substrings with numbers from the substrings without numbers:</p>
<pre class="brush: jscript; title: ; notranslate">
(function() {
  // Regular expression to separate the digit string from the non-digit strings.
  var reParts = /d+|D+/g;

  // Regular expression to test if the string has a digit.
  var reDigit = /d/;

  // Add cmpStringsWithNumbers to the global namespace.  This function takes to
  // strings and compares them, returning -1 if `a` comes before `b`, 0 if `a`
  // and `b` are equal, and 1 if `a` comes after `b`.
  cmpStringsWithNumbers = function(a, b) {
    // Get rid of casing issues.
    a = a.toUpperCase();
    b = b.toUpperCase();

    // Separates the strings into substrings that have only digits and those
    // that have no digits.
    var aParts = a.match(reParts);
    var bParts = b.match(reParts);

    // Used to determine if aPart and bPart are digits.
    var isDigitPart;

    // If `a` and `b` are strings with substring parts that match...
    if(aParts &amp;&amp; bParts &amp;&amp;
        (isDigitPart = reDigit.test(aParts[0])) == reDigit.test(bParts[0])) {
      // Loop through each substring part to compare the overall strings.
      var len = Math.min(aParts.length, bParts.length);
      for(var i = 0; i &lt; len; i++) {
        var aPart = aParts[i];
        var bPart = bParts[i];

        // If comparing digits, convert them to numbers (assuming base 10).
        if(isDigitPart) {
          aPart = parseInt(aPart, 10);
          bPart = parseInt(bPart, 10);
        }

        // If the substrings aren't equal, return either -1 or 1.
        if(aPart != bPart) {
          return aPart &lt; bPart ? -1 : 1;
        }

        // Toggle the value of isDigitPart since the parts will alternate.
        isDigitPart = !isDigitPart;
      }
    }

    // Use normal comparison.
    return a &lt; b ? -1 : (a &gt; b ? 1 : 0);
  };
})();
</pre>
<p>Here is an example of how one could use the above function:</p>
<pre class="brush: jscript; title: ; notranslate">
var fileNames = [
  &quot;Episode 20 - There's More Than One of Everything.mp4&quot;,
  &quot;Episode 4 - The Arrival.mp4&quot;,
  &quot;Episode 7 - In Which We Meet Mr. Jones.mp4&quot;,
  &quot;Episode 15 - Inner Child.mp4&quot;,
  &quot;Episode 6 - The Cure.mp4&quot;,
  &quot;Episode 3 - The Ghost Network.mp4&quot;
].sort(cmpStringsWithNumbers);

alert(fileNames.join('n'));
</pre>
<p>After the above two code blogs run, the following would be alerted to the user:</p>
<pre class="brush: plain; title: ; notranslate">
Episode 3 - The Ghost Network.mp4
Episode 4 - The Arrival.mp4
Episode 6 - The Cure.mp4
Episode 7 - In Which We Meet Mr. Jones.mp4
Episode 15 - Inner Child.mp4
Episode 20 - There's More Than One of Everything.mp4
</pre>
<p>One thing that is important to note is that this comparison function is case-insensitive.  This function is pretty well documented so if you have a need for it in your JScript, HTA <img src='http://cwestblog.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> , or JavaScript file, feel free to use it.</p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/04/10/javascript-comparing-and-sorting-strings-with-numbers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript &#8211; Prototypes, Private Data, &amp; Safe Factories</title>
		<link>http://cwestblog.com/2013/04/03/javascript-prototypes-private-data-safe-factories/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-prototypes-private-data-safe-factories</link>
		<comments>http://cwestblog.com/2013/04/03/javascript-prototypes-private-data-safe-factories/#comments</comments>
		<pubDate>Wed, 03 Apr 2013 06:43:44 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JScript]]></category>
		<category><![CDATA[Function]]></category>
		<category><![CDATA[Private Data]]></category>
		<category><![CDATA[Prototype]]></category>

		<guid isPermaLink="false">http://gotochriswest.com/blog/?p=1713</guid>
		<description><![CDATA[So, after doing even more research on providing prototypal functions access to private data, I came across this article on the Safe Factory Pattern. It is actually similar to my Accessor Verification pattern that I recommended here on Monday. The &#8230; <a href="http://cwestblog.com/2013/04/03/javascript-prototypes-private-data-safe-factories/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>So, after doing even more research on providing prototypal functions access to private data, I came across <a href="http://www.codeproject.com/Articles/133118/Safe-Factory-Pattern-Private-instance-state-in-Jav" title="Safe Factory Pattern - Private Instance State in JavaScript" target="_blank">this article on the <b>Safe Factory Pattern</b></a>.  It is actually similar to my <a href="http://gotochriswest.com/blog/2013/04/01/javascript-prototypal-functions-and-private-data/" title="JavaScript – Prototypal Functions &#038; Private Data" target="_blank"><b>Accessor Verification</b> pattern that I recommended here</a> on Monday.  The quick summary is that by shortening this a bit, you can actually safely achieve private data access from prototypal functions:</p>
<pre class="brush: jscript; title: ; notranslate">
(function(global, returnData, undefined) {
  // Variable returnData is for temporarily storing what
  // will be returned from the openMySafe function.
  // &quot;undefined&quot; is defined this way so that to minify it
  // in closure compiler.
  
  // Gets the private data from the safe that was created
  // and returns it.
  function openMySafe(me) {
    returnData = undefined;
    me._();
    return returnData;
  }

  // Determine if caller is a property when a function is
  // executed.
  function callerExists() {
    return !!callerExists.caller;
  }
  callerExists = callerExists();
  
  // Returns a function that will return the provided
  // private data only when returnData evaluates to true.
  function makeMySafe(privateData) {
    function safe() {
      // If the caller of this function is openMySafe,
      // assign privateData to returnData.
      if(callerExists == (safe.caller == openMySafe)) {
        returnData = privateData;
      }
    };
    return safe;
  }
  
  // Create the Person class in the global namespace.
  var PersonPrototype = (global.Person = function(firstName, lastName) {
    this._ = makeMySafe({
      firstName : firstName,
      lastName : lastName
    });
  }).prototype;
  PersonPrototype.getName = function() {
    var pData = openMySafe(this);
    return pData.firstName + ' ' + pData.lastName;
  };
  PersonPrototype.setFirstName = function(firstName) {
    var pData = openMySafe(this);
    pData.firstName = firstName;
    return this;
  };
  PersonPrototype.setLastName = function(lastName) {
    var pData = openMySafe(this);
    pData.lastName = lastName;
    return this;
  };
})(this);

// Test out the code.
var chris = new Person('Chris', 'West');
alert(chris.setFirstName('C.').setLastName('Webber').getName());

// Make sure the private data is not accessible.
var prefix = chris._() === undefined ? 'un' : '';
// Outputs:  &quot;The private data returned is undefined.&quot;
alert('The private data returned is ' + prefix + 'defined.');
</pre>
<p>This <b>Abbreviated Safe Factory Pattern</b> works for the following reasons:</p>
<ul>
<li>The <code>makeMySafe(<i>{private_data}</i>)</code> function takes the private data associative array object and uses encapsulation to return a function (safe function) which can assign the value to be returned by a safe opener function.</li>
<li>JavaScript is only arguably single-threaded (web-workers and browser events may be the exception but this doesn&#8217;t seem to be explicitly stated); no two threads can run at the same time.</li>
<li>Since JavaScript is single-threaded (or at least one function should execute fully before another starts), we can rely on one control value to determine when private data can be returned by the safe functions.</li>
<li>The <code>openMySafe(<i>{person_object}</i>)</code> function&#8230;
<ol>
<li>takes a person object</li>
<li>sets <code>returnData</code> to <code>undefined</code></li>
<li>calls the safe function produced by <code>makeMySafe(<i>{private_data}</i>)</code> (AKA <code><i>{person_object}</i>._()</code>) to assign the private data object to <code>returnData</code></li>
<li>returns the value of <code>returnData</code> which should be the private data object</li>
</ol>
</li>
</ul>
<p>I actually had to add an if statement to the safe function due to the existence of <code>Function.prototype.caller</code>.  Without this if statement, rogue code could get a reference to openMySafe</code> which would effectively provide access to the private data of an object.  This is actually a deficiency that even exists in the original <code>Safe Factory Pattern</code></p>
<p>If multiple threads could run at once it would be possible for the incorrect private data to get passed back to the wrong class instance.  If you do have to allow your classes to multi-threaded, I would recommend using the <a href="http://gotochriswest.com/blog/2013/04/01/javascript-prototypal-functions-and-private-data/" title="JavaScript – Prototypal Functions &#038; Private Data" target="_blank"><b>Accessor Verification Pattern</b> I suggested in this post</a>.</p>
<p>Again, I invite all JavaScripters to try to find a way to get the private data without modifying the closure.  I am personally convinced that using this <b>Abbreviated Safe Factory Pattern</b> is a fullproof way of allowing prototypal functions access to truly private members.  If you can find a way to disprove me, though, I would be thoroughly impressed (and would much appreciate it)! <img src='http://cwestblog.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/04/03/javascript-prototypes-private-data-safe-factories/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>JavaScript &#8211; Prototypal Functions &amp; Private Data</title>
		<link>http://cwestblog.com/2013/04/01/javascript-prototypal-functions-and-private-data/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-prototypal-functions-and-private-data</link>
		<comments>http://cwestblog.com/2013/04/01/javascript-prototypal-functions-and-private-data/#comments</comments>
		<pubDate>Mon, 01 Apr 2013 04:00:40 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JScript]]></category>
		<category><![CDATA[Function]]></category>
		<category><![CDATA[Private Data]]></category>
		<category><![CDATA[Prototype]]></category>

		<guid isPermaLink="false">http://gotochriswest.com/blog/?p=1697</guid>
		<description><![CDATA[A while back many people responded to this post, helping me see that my solution for providing private data access to prototypal functions was incomplete. Since then, I had been playing around with some possible solutions in my head and &#8230; <a href="http://cwestblog.com/2013/04/01/javascript-prototypal-functions-and-private-data/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>A while back many people responded to <a href="http://gotochriswest.com/blog/2011/05/04/private-variables-in-javascript/" title="Private Variables In JavaScript" target="_blank">this post</a>, helping me see that my solution for providing private data access to prototypal functions was incomplete.  Since then, I had been playing around with some possible solutions in my head and finally came up with two:</p>
<ol>
<li>Prototypal Registry</li>
<li>Accessor Verification</li>
</ol>
<h2><u>Prototypal Registry</u></h2>
<p><b>Prototypal Registry</b> involves using an associative array of all of the original prototypal functions to make sure that the function that is calling the private data accessor function is authentic.  The following source code is an example of a Person class which implements this solution to allow three prototypal functions access to private data:</p>
<pre class="brush: jscript; collapse: true; light: false; title: ; toolbar: true; notranslate">
(function(global) {
  // Get generic hasOwnProperty function just in case it is overwritten.
  var hasOwnProperty = ({}).hasOwnProperty;
  
  // Adds the properties defined in objWithExtensions to objToExtend.
  function extend(objToExtend, objWithExtensions) {
    for(var key in objWithExtensions) {
      if(hasOwnProperty.call(objWithExtensions, key)) {
        objToExtend[key] = objWithExtensions[key];
      }
    }
  }
  
  // Creates a Person class.
  var PersonRegistry = {
    getName : function() {
      var pData = this._('getName');
      return pData.firstName + ' ' + pData.lastName;
    },
    setFirstName : function(firstName) {
      var pData = this._('setFirstName');
      pData.firstName = firstName;
      return this;
    },
    setLastName : function(lastName) {
      var pData = this._('setLastName');
      pData.lastName = lastName;
      return this;
    }
  };
  extend((global.Person = function(firstName, lastName) {
    var pData = {
      firstName : firstName,
      lastName : lastName
    };
    function _(name) {
      return PersonRegistry[name] == _.caller &amp;&amp; pData;
    }
    this._ = _;
  }).prototype, PersonRegistry);
})(this);

var chris = new Person('Chris', 'West');
alert(chris.setFirstName('Christopher').setLastName('Webber').getName());
</pre>
<p>The problem with this first solution is the fact that it cannot be guaranteed to work in all environments.  Strict mode, Opera 10, BESEN and Rhino 1.7 don&#8217;t support the function &#8220;<code>caller</code>&#8221; property (<a href="http://kangax.github.com/es5-compat-table/non-standard/" target="_blank">better breakdown</a>), thusly preventing this solution from working in those environments.  Due to this issue, I started thinking about a different solution.</p>
<h2><u>Accessor Verification</u></h2>
<p>The true issue with my original solution (from <a href="http://gotochriswest.com/blog/2011/05/04/private-variables-in-javascript/" title="Private Variables In JavaScript" target="_blank">this post</a> and <a href="http://gotochriswest.com/blog/2012/11/14/javascript-classes-private-members-and-prototypal-inheritance/" title="JavaScript – Classes, Private Members, &#038; Prototypal Inheritance" target="_blank">this post</a>) was the fact that you could override the private data accessor and steal the secret key that was used by all other private data accessors.  This then would give that rogue code access to the private data of instances of all such classes.  <b>Accessor Verification</b> prevents rogue outside code from being able to do that.  Using this scripting pattern, you create a function which is called to then verify that the private data accessor function hasn&#8217;t been tampered with.  After the accessor function is verified, it is then called with the secret key (accessible only by code within the closure) to get access to the private data.  The following source code is an example of a Person class which implements this solution to allow three prototypal functions access to private data:</p>
<pre class="brush: jscript; collapse: true; light: false; title: ; toolbar: true; notranslate">
(function(key, global) {
  // Creates a private data accessor function.
  function _(pData) {
    return function(aKey) {
      return aKey === key &amp;&amp; pData;
    };
  }
  
  // Private data accessor verifier.  Verifies by making sure that the string
  // version of the function looks normal and that the toString function hasn't
  // been modified.  NOTE:  Verification can be duped if the rogue code replaces
  // Function.prototype.toString before this closure executes.
  function $(me) {
    if(me._ + '' == _asString &amp;&amp; me._.toString === _toString) {
      return me._(key);
    }
  }
  var _asString = _({}) + '', _toString = _.toString;
  
  // Creates a Person class.
  var PersonPrototype = (global.Person = function(firstName, lastName) {
    this._ = _({
      firstName : firstName,
      lastName : lastName
    });
  }).prototype;
  PersonPrototype.getName = function() {
    var pData = $(this);
    return pData.firstName + ' ' + pData.lastName;
  };
  PersonPrototype.setFirstName = function(firstName) {
    var pData = $(this);
    pData.firstName = firstName;
    return this;
  };
  PersonPrototype.setLastName = function(lastName) {
    var pData = $(this);
    pData.lastName = lastName;
    return this;
  };
})({}, this);

var chris = new Person('Chris', 'West');
alert(chris.setFirstName('Christopher').setLastName('Webber').getName());
</pre>
<p>The above solution should work in all JavaScript/JScript environments.  If the private accessor function is overriden, the call by any prototypal function will fail because the verification function will notice that it has been tampered with and <code>undefined</code> will be returned to the prototypal function as the private data container.  Neither by using the previous line of thinking (<a href="http://gotochriswest.com/blog/2011/05/04/private-variables-in-javascript/#comment-791" title="Private Variables In JavaScript" target="_blank">suggested by Esailija</a>), nor by using any other have I been able to extract private data without modifying the original code (that which appears in the closure).  The only time when rogue code could dupe the verifier function is if the rogue code overrides <code>Function.prototype.toString</code> before the closure defining the classes is executed.  In that case, though, you may have more issues than just those encountered with your private data becoming public. <img src='http://cwestblog.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>I would be interested in seeing if any readers can find a way to get access to the private data object with code that runs after the class is defined.  If you are good at JavaScript, and think you can figure it out, let me know, but I believe this is a rock solid solution.  <img src='http://cwestblog.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' />  Happy hacking!!!</p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/04/01/javascript-prototypal-functions-and-private-data/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>POW Answer &#8211; JavaScript Self Inequality</title>
		<link>http://cwestblog.com/2013/03/25/pow-answer-javascript-self-inequality/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=pow-answer-javascript-self-inequality</link>
		<comments>http://cwestblog.com/2013/03/25/pow-answer-javascript-self-inequality/#comments</comments>
		<pubDate>Mon, 25 Mar 2013 04:00:23 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JScript]]></category>

		<guid isPermaLink="false">http://gotochriswest.com/blog/?p=1706</guid>
		<description><![CDATA[As two people indicated in their comments in the original POW post, the answer is NaN. You can even do the following to check it: Weird stuff, right?!?!?!]]></description>
				<content:encoded><![CDATA[<p>As two people indicated in their comments in the <a href="http://gotochriswest.com/blog/2013/03/18/pow-javascript-self-inequality/" title="POW – JavaScript Self Inequality" target="_blank">original POW post</a>, the answer is <code>NaN</code>.  You can even do the following to check it:</p>
<pre class="brush: jscript; title: ; notranslate">
alert(NaN === NaN);  // outputs false
</pre>
<p>Weird stuff, right?!?!?!</p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/03/25/pow-answer-javascript-self-inequality/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>POW &#8211; JavaScript Self Inequality</title>
		<link>http://cwestblog.com/2013/03/18/pow-javascript-self-inequality/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=pow-javascript-self-inequality</link>
		<comments>http://cwestblog.com/2013/03/18/pow-javascript-self-inequality/#comments</comments>
		<pubDate>Mon, 18 Mar 2013 04:00:26 +0000</pubDate>
		<dc:creator>Chris West</dc:creator>
				<category><![CDATA[Blog]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JScript]]></category>
		<category><![CDATA[Problem of the Week]]></category>
		<category><![CDATA[Function]]></category>

		<guid isPermaLink="false">http://gotochriswest.com/blog/?p=1683</guid>
		<description><![CDATA[Assuming a normal JavaScript engine, what could you possibly pass into the following mystery() function that would not thrown an error? As is normal, this answer will be shown a week from when it was posted and will be linked &#8230; <a href="http://cwestblog.com/2013/03/18/pow-javascript-self-inequality/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Assuming a normal JavaScript engine, what could you possibly pass into the following <code>mystery()</code> function that would not thrown an error?</p>
<pre class="brush: jscript; title: ; notranslate">
function mystery(a) {
  if (a === a) {
    throw new Error('The first argument has self equality.');
  }
}
</pre>
<p><del datetime="2013-03-25T04:00:00+00:00">As is normal, this answer will be shown a week from when it was posted and will be linked to from here.</del>The answer to this POW can now be found <a href="http://gotochriswest.com/blog/2013/03/25/pow-answer-javascript-self-inequality/" title="POW Answer – JavaScript Self Inequality" target="_blank">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://cwestblog.com/2013/03/18/pow-javascript-self-inequality/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
