Condensed Code

Or how I learned to stop worrying and love the shorthand

I like small, useful code bites, and I love Javascript. I made this webpage to showcase common code snippets at their minimum necessary size. Most of these code examples are smaller than a tweet. You should be able to try any of these in the console of your browser.

WARNINGIt's worth mentioning, I'm using a lot of weird shorthand notations on these examples. Most of them assume that the correct arguments have been provided, and many of the condensed versions only work up to a certain point. Some of the verbose examples actually add functionality and are not 1-1 comparisons. Basically I'm saying that this is by no means a scientific endeavor and is more of an art project.

Leading Zeros

Description - Add a number of leading zeros to a number. The first argument is the number to be processed, and the second argument is the amount of zero places (including the process number) to add. A string is returned from this function.

Condensed - 54 characters
  1. var lz=function(n,e){return (+n+Math.pow(10,e)+'').substr(1)}
Verbose - 132 characters
  1. var leadingZeros = function(number, exponent){
  2. var zeros = new Array( exponent - number.toString().length + 1 );
  3. return zeros.join( '0' ) + number;
  4. }
Example
  1. > lz(4,3);
  2. < "004"
Random Boolean

Description - Return a random true or false value. A smaller version provided by x-skeww.

Condensed - 36 characters
  1. var rb=function(){return Math.random()<0.5}
Verbose - 86 characters
  1. var randomBoolean = function(){
  2. if(Math.random() > 0.5) {
  3. return true;
  4. } else {
  5. return false;
  6. }
  7. }
Example
  1. > rb();
  2. < false
Random number less than Max

Description - Return a random number between zero and 1 less than a maximum amount.

Condensed - 39 characters
  1. var rm=function(m){return ~~(Math.random()*m)}
Verbose - 57 characters
  1. var randomMax = function(max){
  2. return Math.floor(Math.random() * max);
  3. }
Example
  1. > rm(10);
  2. < 7
Random number between a Range

Description - Return a random number between a minimum and maximum number.

Condensed - 55 characters
  1. var rr=function(n,x){return Math.round(Math.random()*(x-n))+n}
Verbose - 76 characters
  1. var randomRange = function(min, max){
  2. return Math.round(Math.random() * (max - min)) + min;
  3. }
Example
  1. > rr(5,10);
  2. < 7
Random Boolean, Max, or Range

Description - Return any of the random values based on arguments provided. If no arguments are sent, a random boolean is returned. If 1 argument is sent, a random number from 0 to 1 less than the argument is returned. If 2 arguments are sent, a random number from the minimum to the maximum is returned.

Condensed - 87 characters
  1. var rn=function(n,x){var r=Math.random();return !x?(!n?r<0.5:~~(r*n)):Math.round((r*(x-n))+n)}
Verbose - 227 characters
  1. var randomNumber = function(min,max){
  2. var rand = Math.random();
  3. if(max === void(0)) {
  4. if(min === void(0)) {
  5. return rand < 0.5;
  6. } else {
  7. return Math.floor(rand * min);
  8. }
  9. } else {
  10. return Math.round((rand * (max - min)) + min);
  11. }
  12. }
Example
  1. > rn();
  2. < true
  3. > rn(10);
  4. < 4
  5. > rn(5,10);
  6. < 7
Number with Commas

Description - Return a number formatted into a string with commas added to the integer portion of the number. This uses modified code from a stackoverflow answer.

Condensed - 72 characters
  1. var nc=function(n){return (n+'').replace(/\B(?=(?=\d*\.)(\d{3})+(?!\d))/g,',')}
Verbose - 84 characters
  1. var numberCommas = function(num){
  2. return String(num).replace(/\B(?=(?=\d*\.)(\d{3})+(?!\d))/g, ',');
  3. }
Example
  1. > nc(2454542365.346245);
  2. < "2,454,542,365.346245"
Money Number with Commas

Description - Return a number formatted into a string with commas added to the integer portion of the number. A dollar sign will be appended to the front of the string. A second argument can be added to define how many decimal points are desired.

Condensed - 104 characters
  1. var mc=function(n,d){d=d!==void(0)?d:2;return ('$'+n.toFixed(d)).replace(/\B(?=(?=\d*\.)(\d{3})+(?!\d))/g,',')}
Verbose - 157 characters
  1. var moneyCommas = function(num,decimal){
  2. if(decimal === void(0)) {
  3. decimal = 2;
  4. }
  5. return String('$' + n.toFixed(decimal)).replace(/\B(?=(?=\d*\.)(\d{3})+(?!\d))/g,',');
  6. }
Example
  1. > mc(2454542365.346245);
  2. < "$2,454,542,365.35"
Randomize Array (Inside-Out)

Description - Return a new array that has been shuffled into a random order using an "Inside-Out" method.

Condensed - 117 characters
  1. var ro=function(a){var b=a.slice(0),c=[];while(b.length){c.push(b.splice(Math.floor(Math.random()*b.length),1)[0])}return c}
Verbose - 274 characters
  1. var randomArrayShuffle = function(arr){
  2. var tempArray1 = arr.slice(0);
  3. var tempArray2 = new Array();
  4. var tempObject;
  5. while(tempArray1.length > 0){
  6. tempObject = Math.floor(Math.random() * tempArray1.length);
  7. tempArray2.push(
  8. tempArray1.splice(tempObject, 1)[0]
  9. )
  10. }
  11. return tempArray2;
  12. }
Example
  1. > ro([1,2,3,4,5,6]);
  2. < [2, 6, 1, 5, 4, 3]
Randomize Array (Fisher-Yates)

Description - Return a new array that has been shuffled into a random order using a "Fisher-Yates" method.

Condensed - 122 characters
  1. var fy=function(a){for(var b=a.slice(0),i=0,l=b.length,j,t;i<l;i++){j=~~(Math.random()*(l-i))+i;t=b[i];b[i]=b[j];b[j]=t}return b}
Verbose - 413 characters
  1. var fisherYatesShuffle = function(arr){
  2. var tempArray = arr.slice(0);
  3. var length = tempArray.length;
  4. var randomIndex;
  5. var tempObject;
  6. for(var incrementor = 0; incrementor < length; incrementor += 1){
  7. randomIndex = Math.floor(Math.random() * (length - incrementor)) +incrementor;
  8. tempObject = tempArray[incrementor];
  9. tempArray[incrementor] = tempArray[randomIndex];
  10. tempArray[randomIndex] = tempObject;
  11. }
  12. return tempArray;
  13. }
Example
  1. > fy([1,2,3,4,5,6]);
  2. < [2, 6, 1, 5, 4, 3]
Randomize Array using sort()

Description - Return a new array that has been shuffled into a random order using the Javascript sort() function. Provided by ZyklusDieWelt.

Condensed - 82 characters
  1. var as=function(a){var b=a.slice(0);b.sort(function(){return Math.random()-.5});return b}
Verbose - 130 characters
  1. var arrayShuffleWithSort = function(arr){
  2. var tempArray = arr.slice(0);
  3. tempArray.sort(function() {
  4. return Math.random() - 0.5;
  5. });
  6. return tempArray;
  7. }
Example
  1. > as([1,2,3,4,5,6]);
  2. < [2, 6, 1, 5, 4, 3]
Time Difference

Description - The first time this function is called it sets a timestamp onto a static variable. The second time it is called, it returns a time difference between the first timestamp and the current timestamp.

Condensed - 82 characters
  1. var td=function(){if(!td.t)td.t=new Date();else{td.r=new Date()-td.t;td.t=0;return td.r}}
Verbose - 209 characters
  1. var timeDifference = function(){
  2. if(!timeDifference.time) {
  3. timeDifference.time = new Date();
  4. } else {
  5. timeDifference.result = new Date() - timeDifference.time;
  6. timeDifference.time = 0;
  7. return timeDifference.result;
  8. }
  9. }
Example
  1. > td();
  2. < undefined
  3. > td();
  4. < 300
Node index in Parent

Description - Return the index of the current node inside its parent node.

Condensed - 61 characters
  1. var ni=function(n){return [].indexOf.call(n.parentNode.children, n)}
Verbose - 167 characters
  1. var nodeIndex = function(node){
  2. var parentChildren = node.parentNode.children;
  3. for(var i = 0, l = parentChildren.length; i < l; i++) {
  4. if(parentChildren[i] == node) return i;
  5. }
  6. }
Example
  1. > ni(document.querySelectorAll('dt')[2]);
  2. < 6
Mustache Template

Description - Much like many templating libraries, there are two arguments. A template string must be provided, and an object representing all the data for the template. Use {{data}} double mustaches to represent properties of the second argument object. These property values will be inserted into the template.

Condensed - 85 characters
  1. var mt=function(t,d){for(var i in d){t=t.replace(RegExp('\{\{'+i+'}}','g'),d[i]);}return t;}
Verbose - 242 characters
  1. var mustacheTemplate = function(template,data){
  2. if(!template || !data) return template||'';
  3. for(var key in data){
  4. if(data.hasOwnProperty(key) === false) continue;
  5. template = template.replace(RegExp('\{\{' + key + '}}', 'g'), data[key]);
  6. }
  7. return template;
  8. }
Example
  1. > mt('{{amount}} apples',{amount:8});
  2. < "8 apples"
PHP Style Replace from Array

Description - PHP has the ability to use arrays as the arguments of preg_replace, while Javascript does not have this functionality by default for its .replace() function. The first argument should be an array of RegExp objects, the second argument should be an array of string replacements of the same size as the first array, and the third argument should be the replacement context string.

Condensed - 63 characters
  1. var ra=function(r,s,c){for(var i in r)c=c.replace(r[i],s[i]);return c}
Verbose - 198 characters
  1. var replaceFromArray = function(searchList,replaceList,context){
  2. for(var key = 0, length = searchList.length; key < length; key += 1) {
  3. context = context.replace(searchList[key],replaceList[key]);
  4. }
  5. return context;
  6. }
Example
  1. > ra([/re/g,/apples/g],['dis','bananas'],'replace the apples');
  2. < "displace the bananas"