views:

1400

answers:

29

This is a question to put as many interesting and useful JavaScript functions written in one line as we can. I made this question because I'm curious how many people around like the art of one-Line programming in JavaScript, and I want to see their progress in action.

Put variations of each code inside comments.

+6  A: 

To start, here is first one:

Human readable number in javascript:

readableNumberLimiter = function (number,limiter)
{
  return number.toString().replace(
     new RegExp(
         "(^\\d{"+(number.toString().length%3||-1)+"})(?=\\d{3})"),
         "$1"+limiter
         ).replace(/(\d{3})(?=\d)/g,"$1"+limiter);
}

Example of use:

readableNumberLimiter(12345678,",");

Returns:

"12,345,678"

Example 2:

readableNumberLimiter(12345678,".");

Returns:

"12.345.678"

Example 3:

readableNumberLimiter(12345678," ");

Returns:

"12 345 678"
Wilq32
No internationalisation? :(
Rob
@Rob: ? - the limiter is user-defined!
Christoph
There is also: new Number(345).toLocaleString()But not working at least in Chrome (probably in IE too)
Wilq32
Support for decimals would be useful.
Ates Goral
For internationalisation, you would need to allow the number of digits per group to be variable as well.
Marcus Downing
+10  A: 

The sign() function:

function sign(x) {
    return (x > 0) - (x < 0);
}
Christoph
Could you give me an example of where this function has a use? I've never come across something like this before. Thanks.
kouPhax
This is nice function - i tried to make something shorter but failed. Simple but nice - i like it :)
Wilq32
Where would you use it Wilq32?
kouPhax
@kouPhax I have no exacly idea now, but from what I remember there is some math related stuff that needs this functionality
Wilq32
Determining the sign of a number is pretty basic; I used this when I implemented a numeric tuple type to compute if two tuples were comparable (ie both values <, = or >)
Christoph
@kouPhax: This is useful when you need to deal with a number's absolute value while retaining its sign. e.g. `width = sign(width) * (Math.abs(width) + 15); // increase width by 15`
Ben Blank
I love this concise implementation!
Ates Goral
This is also called the signum function, and it's useful in many applications. http://en.wikipedia.org/wiki/Sign_function
Nosredna
+4  A: 

This isn't one line, but it is short and useful.

Here is a function to add another function to a callback function:

function addCallback(oldFunc, newFunc) {
    oldFunc = oldFunc || function () {};
    return function () {oldFunc(); newFunc();};
}

Here's an example usage:

document.onload = addCallback(window.onLoad, function () {alert("me too!"); });
document.onload = addCallback(window.onLoad, function () {alert("me three!"); });

In this example, the new function, as well as whatever was there before (if there was anything) will be run when window.onload is called.

Edit: The following variant should be more useful, as it preserves this and arguments and returns a value somewhat meaningful for listeners:

function chain(f1, f2) {
    return typeof f1 !== 'function' ? f2 : function() {
     var r1 = f1.apply(this, arguments),
      r2 = f2.apply(this, arguments);
     return typeof r1 === 'undefined' ? r2 : (r1 && r2);
    };
}
pkaeding
This is one line :) a little mod :)function addCallback(oldFunc, newFunc) { return function () { (!!oldFunc)?oldFunc():null; (!!newFunc)?newFunc():null;};}
Wilq32
Christoph
@christoph: !! is here to make sure that its defined, of course that would be useful when parsing numbers, and numbers cant be executed so... well you got right - !! are not needed :) Also I like this functionality of oldFunc )
Wilq32
+4  A: 

I do this kind of thing on prototypes, a few exempli gratias (I hope the purpose and returns are obvious)

Date.prototype.daysInMonth = function ()
{
    var x = 31;
    switch (this.getMonth()) //zero-index
    {
     case 1:  x = (this.isLeapYear()? 29 : 28);break;
     case 3:
     case 5:
     case 8:
     case 10: x = 30;
    }
    return x;
};

Date.prototype.isLeapYear = function ()
{
    var y = this.getFullYear();
    return (y%400==0 || (y%100!=0 && y%4==0));
};

Date.prototype.unbox = function ()
{
    return new Date(this);
}

String.prototype.reverse = function () 
{
    return this.split('').reverse().join('');
};
annakata
@Gumbo: good idea, but if you benchmark it you'll actually see that the switch based technique is about 33-40% faster. Creating all those arrays is relatively expensive compared to switch.
annakata
But asking for “this.isLeapYear” is wrong as it returns a function that always evaluates to true. It must be “this.isLeapYear()”.
Gumbo
ha - you totally got me there (fixed, thanks)
annakata
Date.prototype.daysInMonth = function ()Date.prototype.isLeapYear = function ()In fact they are not one-line functions. They use an declaration of local variable. And its hard to tell that switch case is trully oneline technique (or maybe it is?)
Wilq32
well you could do it inline, but it would be inefficient, which was kind of my point
annakata
Should use getFullYear() in isLeapYear since getYear() was supposed to give the year since 1900.
some
@some - that's my bad, I override getYear to point to get FullYear in my library code
annakata
Also, daysInMonth should be using e.g. "return 30;" instead of "x = 30;" — save yourself a local variable and a GOTO.
Ben Blank
Date.prototype.isLeapYear = function (){ return ((arguments[0]=this.getFullYear())%400==0 || (arguments[0]%100!=0 };This should do oneline ?
Wilq32
@Ben - how does this save a "GOTO"? and I value a single exit point > saving a local var. @Wilq - yeah, it would but readability > arbitrary one line goal except in this question
annakata
+13  A: 
String.prototype.trim = function(){ this.replace( /^\s+|\s+$/g, '' ); }
meouw
For faster implementations, see http://blog.stevenlevithan.com/archives/faster-trim-javascript
Gumbo
+7  A: 

A clone() function to add 'real' prototypal inheritance:

function clone(obj) {
    return typeof obj === 'undefined' ?
     this : (clone.prototype = Object(obj), new clone);
}
Christoph
+1  A: 

A typeOf() function which returns the value's type (lower case) for primitives and the values Class (upper case, according to the [[Class]] property) for objects:

function typeOf(value) {
    var type = typeof value;
    return type === 'object' ? (value === null ? 'null' :
     Object.prototype.toString.call(value).match(/^\[object (.*)\]$/)[1]) :
     type === 'function' ? 'Function' : type;
}

Known bugs in IE:

  • built-in functions may be considered 'Object'
  • calls to COM+ objects may return values of type 'unknown'

If you don't care if a value is primitive or boxed, you can use typeOf(...).toLowerCase().

Christoph
@Prestaul - having been through similar with Christoph this morning - hi, Christoph :) - I wonder what your rationale for labelling String/string as a genral shortcoming is? The native String() method is a wrapper on the primitive type, the two things are *not* the same, but the type can box up.
annakata
(i.e. I think Christoph's method is correct and this is not a shortcoming)
annakata
@annakata: hi there, too ;) And discerning between primitives and objects by case seems practical - even if 'number' means "primitive of type Number" and 'Number' means "Object of [[Class]] Number"
Christoph
+3  A: 
function coalesce() {
    for (var i=0; i<arguments.length; i++) {
        if (arguments[i] !== null) {
            return arguments[i];
        }
    }
    return null;
}
Gumbo
What is an example of usage? I don't think that I understand the usefulness of a function that returns the first non-null argument...
Prestaul
@Prestaul, var someValue = coalesce(parameter, "default");
Matthew Crumley
@Matthew: This is generally written as `someValue = parameter || "default"`; and the check `!== null` won't work - it should be `!== undefined`
Christoph
With a coalesce function, you can check multiple values though. I guess that wasn't the best example, how about: var someValue = coalesce(parameter, defaults.defaultValue, "local fallback value")? And yes, I would probably check for null or undefined.
Matthew Crumley
+3  A: 

A classic:

function IsDefined(variable)
{
  return !(typeof(window[variable]) == 'undefined');
}

Usage should be clear.

It's not clear from the name of the function that it only checks the global scope. It will also return false if the global variable has the primitive value "undefined". This returns true regardless of value, if the variable exists: function isGlobalyDefined(name){ return name in window; }
some
Yes, IdGlobalDefined would be more proper name for this function I think :)
Wilq32
return typeof window[variable] != "undefined';
Ates Goral
A: 

Show seconds in format minutes:seconds

function secondstominutes(secs)
{
   return ((arguments[1]=(Math.floor(secs/60)))<10?"0":"")+arguments[1]+":"+((arguments[2]=secs%60)<10?"0":"") + arguments[2];
}

Example:

secondstominutes(1); // result 00:01

secondstominutes(50); // result 00:50

secondstominutes(61); // result 01:01

Wilq32
+2  A: 

Date formatter with easy-to-remember format specifiers:

function formatDate(date, fmt) {  
    return fmt.replace(  
        /\{([^}:]+)(?::(\d+))?\}/g,  
        function (s, comp, pad) {  
            var fn = date["get" + comp];  

            if (fn) {  
                var v = (fn.call(date) +  
                    (/Month$/.test(comp) ? 1 : 0)).toString();  

                return pad && (pad = pad - v.length)  
                    ? new Array(pad + 1).join("0") + v  
                    : v;  
            } else {  
                return s;  
            }  
        });  
};

Whatever you enclose inside curly brackets will be used as a format specifier:

var now = new Date();  

alert(formatDate(now, "This is the year {FullYear}"));  
// Output: This is the year 2008

You can also zero-pad values:

alert(formatDate(now, "{FullYear}-{Month:2}-{Date:2}"));  
// Output: 2008-09-02  
alert(formatDate(now, "{Hours:2}:{Minutes:2}:{Seconds:2}.{Milliseconds:3}"));  
// Output: 15:47:32.156

If an unknown format specifier is used, the format specifier will be used as it is:

alert(formatDate(now, "{Hourz} hours {Minutes} minutes"));  
// Output: {Hourz} hours 51 minutes

Invalid format specifiers are also handled gracefully:

alert(formatDate(now, "{FullYear:}));  
// Output: {FullYear:}

All Date instance getters are recognized as valid format specifiers.

Ates Goral
+1  A: 
/** 
 * Left-pad a number with zeros so that it's at least the given 
 * number of characters long 
 * @param n   The number to pad 
 * @param len The desired length 
 */  
function leftPad(n, len) {  
    return (new Array(len - String(n).length + 1)).join("0").concat(n);  
}

alert(leftPad(42, 6)); // Gives "000042"
Ates Goral
This only works for positive numbers: leftPad(-42, 6) == "000-42"
Matthew Crumley
True. Typically, it's the positive numbers that are subject to zero-padding. I don't recall seeing any zero-padded negative numbers...
Ates Goral
+1  A: 

Rounding a given decimal number to a given number of significant figures (or digits):

function sigFigs(n, sig) {  
    var mult = Math.pow(10,  
        sig - Math.floor(Math.log(n) / Math.LN10) - 1);  
    return Math.round(n * mult) / mult;
}  

alert(sigFigs(1234567, 3)); // Gives 1230000
alert(sigFigs(0.06805, 3)); // Gives 0.0681
alert(sigFigs(5, 3));       // Gives 5

Not exactly one line, but close :)

Ates Goral
If you want make it one line: function sigFigs(n, sig) { return Math.round((arguments[2]=Math.pow(10,sig - Math.floor(Math.log(n) / Math.LN10) - 1))* n) / arguments[2];}
Wilq32
+1  A: 
String.prototype.replaceAll = function(target, replacement) {
    return this.replace(new RegExp(target, "g"), replacement);
};

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
};

Array.prototype.contains = function(element) {
    var i = this.length;
    while (i--) {
        if (this[i] === element) {
            return true;
        }
    }
    return false;
};

Array.prototype.clear = function() {
    this.length = 0;
};
steve_c
Faster replacement: return this.split(target).join(replacement);
Ates Goral
@Ates Goral: but the split/join method doesn't take regex targets, right?
Jens Roland
@Jens Roland: `split` does accept regex: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
Ates Goral
+3  A: 

Divides an array in several arrays of a given maximum size

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/array/chunk [rev. #1]

function chunk(a, s){
    for(var x, i = 0, c = -1, l = a.length, n = []; i < l; i++)
        (x = i % s) ? n[c][x] = a[i] : n[++c] = [a[i]];
    return n;
}

Example
Input :

chunk([1,2,3,4,5,6,7], 3)

Output:

[[1,2,3],[4,5,6],[7]]

Jader Dias
A: 

Rotates the arrays elements faster than "array.unshift(array.pop())" or "array.push(array.shift())".

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/rotate [rev. #2]

rotate = function(a, p){
    for(var l = a.length, p = (Math.abs(p) >= l && (p %= l), p < 0 && (p += l), p), i, x; p; p = (Math.ceil(l / p) - 1) * p - l + (l = p))
        for(i = l; i > p; x = a[--i], a[i] = a[i - p], a[i - p] = x);
    return a;
};

Examples:
rotate([1,2,3,4,5], 2) = [4, 5, 1, 2, 3]
rotate([1,2,3,4,5], -2) = [3, 4, 5, 1, 2]

Jader Dias
A: 

Escape HTML characters:

function htmlEscape(s) {
    return s.replace(/([&<>])/g,
        function (c) {
            return "&" + {
                "&": "amp",
                "<": "lt",
                ">": "gt"
            }[c] + ";";
        });
}

Add &quot; to the soup if you want.

Ates Goral
+5  A: 

Courtesy of Mathieu "p01" Henri, make any function chainable:

function chain(fn) {
    return function() {
        return fn.apply(this, arguments) || this;
    }
}

For example:

CanvasRenderingContext2D.prototype.fillRect =
    chain(CanvasRenderingContext2D.prototype.fillRect);

//...

ctx.fillRect(0, 0, 10, 10).fillRect(90, 90, 10, 10).fillRect(0, 10, 100, 10);

(Mathieu used this technique to make <canvas> methods chainable and landed the first place at a 20-liner competition over at OZONE Asylum.)

Ates Goral
great one!:) I like it
Wilq32
A: 

Remove one or multiple parameters from a query string:

function removeQueryStringParam(queryString, param) {
    return queryString
        .replace(
            new RegExp("(&?)(?:"
                + (param.join ? param.join("|") : param)
                + ")=[^&]*&?", "g"),
            "$1")
        .replace(/([^&?]*)(?:&|\?)$/, "$1"); 
}

param can be the name of a single parameter or an array of parameter names. The original query string may optionally begin with a "?" or "&". When all parameters are removed, the result becomes an empty string.

Example:

removeQueryStringParam("foo=1&param2=2&bar=3&param4=4", [ "foo", "bar" ]));
// Results in "param2=2&param4=4"
Ates Goral
+1  A: 

Checking for an Array

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

First, we ask if the value is truthy. We do this to reject null and other falsy values. Second, we ask if the typeof value is 'object'. This will be true for objects, arrays, and (weirdly) null. Third, we ask if the value has a length property that is a number. This will always be true for arrays, but usually not for objects. Fourth, we ask if the value contains a splice method. This again will be true for all arrays. Finally, we ask if the length property is enumerable (will length be produced by a for in loop?). That will be false for all arrays. This is the most reliable test for arrayness that I have found. It is unfortunate that it is so complicated.

Having such a test, it is possible to write functions that do one thing when passed a single value and lots of things when passed an array of values.

Taken from JavaScript: The Good Parts, by Douglas Crockford.

Edit by Christoph:

I don't think this is very useful. If you want to test if obj is a real JavaScript array, use

Object.prototype.toString.call(obj) === '[object Array]'

This is guaranteed to work by ECMA-262. If you want to check for non-array array-like objects, there's really not much you can do aside from

typeof obj.length === 'number'
Andreas Grech
+6  A: 

A function to test if the current browser is Internet Explorer:

function isIE() {
    return '\v' == 'v';
}

Others really short functions to test the browser can be found here.

romaintaz
This one is great:)
Wilq32
Upvote for link to The Spanner. I try never to use hacks myself, but I *am* impressed with people who find lots of really nifty ones.
Jens Roland
A: 
String.prototype.strip_tags = function() {
  return this.replace(/<[^>]+>/gi,"");
}

Strip all HTML elements.

Zurahn
A: 

Coming late to the table here but when you're not planning on making use of a full framework like JQuery or Mootools etc I find this one to be indispensible:

function getElementsByClassName(name, parent){
    for(var o = [], n = new RegExp("\\b" + name.replace(/([(){}|*+?.,^$\[\]\\])/g, "\\\$1") + "\\b"), l = (parent || document).getElementsByTagName("*"), i = l.length; i--;)
     n.test(l[i].className) && (o[o.length] = l[i]);
    return o;
}

Not quite one line perhaps but hey...

Ola Tuvesson
+1  A: 

Not one liners, but short enough:

String.prototype.repeat = function(iN){
     var i = parseInt(iN,10) || 2, sOut = [];
     if (this instanceof String && i) {
      do {
         sOut.push(this);
      } while (--i && i > 0);
     }
     return sOut.join('');
};
//Example: 
alert(('-').repeat(10)); //=> '----------'

Number.prototype.between = function()
 { return this>arguments[0] && this<arguments[1]; };
//example
alert((23).between(10,30)); //=> true
alert((23).between(33,40)); //=> false

Function to extract a float from a number string (locale independent)

function extractFloat() {
    var  x = arguments[0].split(/,|\./),
        x2 = x.join('').replace(new RegExp(x[x.length-1]+'$'),'.'+x[x.length-1]);
    return parseFloat(x2);
}
//example:
extractFloat('1,239.4');   //=> 1239.4
extractFloat('1.239,4');   //=> 1239.4
extractFloat('a1.239,b4'); //=> NaN
KooiInc
Upvote for elegant extractFloat function
Jens Roland
A: 

A real one liner: find out if a date is valid:

function dateOK(Y, M, D) {
    return D > 0 &&
        (D <= [, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][M] ||
        D == 29 && M == 2 && Y % 4 == 0 && (Y % 100 > 0 || Y % 400 == 0));
}
KooiInc
A: 
String.prototype.ellipse = function(len) { 
  return (this.length > len) ? this.substr(0, len) + "..." : this; 
}

Useful for adding ellipses on strings longer then len.

tj111
A: 
Array.prototype.lpush = function(item) {
  this.unshift(item); return this;
}

Useful for adding items to the beginning of the array and getting the array back instead of its length.

while (cycle)
  var foo = arr.lpush(foo).pop();
tj111
+1  A: 

The worse I've written:

From here: http://jsfromhell.com/classes/binary-parser

for(var offsetLeft, offsetRight = start % 8, curByte = this.buffer.length - (start >> 3) - 1, lastByte = this.buffer.length + (-(start + length) >> 3), diff = curByte - lastByte, sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[ lastByte++ ] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); diff; sum += shl(this.buffer[lastByte++ ], (diff-- << 3) - offsetRight);

From here: http://jsfromhell.com/forms/masked-input

(!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ? r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0] : (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ? r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();

From here: http://jsfromhell.com/math/closest-circle-point

return function(x, y, x0, y0){return Math.sqrt((x -= x0) * x + (y -= y0) * y);}(px, py, x, y) > ray ? {x: Math.cos(tg = Math.atan2(py - y, px - x)) * ray + x, y: Math.sin(tg) * ray + y} : {x: px, y: py};

:)

+1  A: 
// Javascript modulus operator always returning a positive number
Number.prototype.mod = function(n) {
    return ((this%n)+n)%n;
}

Pure Javascript:

var num = -2;
alert(num % 10); // will output -2

Using the mod function above:

var num = -2;
alert(num.mod(10)); // will output 8

Useful in situations where the result of the modulo operator is used to do a lookup in an array.

Jens Roland