Skip to main content

Don’t reinvent the wheel: Some useful JS libraries

 

It is very common to see “Utility” file in many project, which have all commonly used functions. In other word you can say it is kitchen sink file, where people dump all common functions. Before you realize it grows more than 1000 lines and become a maintenance hell.

So keep in mind, each time when you write a new class or function you are increasing the project maintenance coast.

 

There are few things you should consider before writing the code

  • Know Your Library – Most of the library has some utility functions so keep exploring it.
  • Use Utility Library – If existing library doesn't have needed functionality then always consider using 3rd party Utility Library with good test converge.

 

Some of my favourite libraries

 

Underscore JS 

It is one of the best utility library, which has collection of most commonly used functions. Here are few function with example code.

 

Each

_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...
_.each({one : 1, two : 2, three : 3}, function(num, key){ alert(num); });
=> alerts each number in turn...

Map

_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]

Filter

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]

Pluck

var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]

 Union

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]

Intersection 

_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]

 Keys

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

 Values

_.values({one : 1, two : 2, three : 3});
=> [1, 2, 3]

Escape

_.escape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"

 Chain

var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
var youngest = _.chain(stooges)
  .sortBy(function(stooge){ return stooge.age; })
  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  .first()
  .value();
=> "moe is 21"

and more

var lyrics = [
  {line : 1, words : "I'm a lumberjack and I'm okay"},
  {line : 2, words : "I sleep all night and I work all day"},
  {line : 3, words : "He's a lumberjack and he's okay"},
  {line : 4, words : "He sleeps all night and he works all day"}
];

_.chain(lyrics)
  .map(function(line) { return line.words.split(' '); })
  .flatten()
  .reduce(function(counts, word) {
    counts[word] = (counts[word] || 0) + 1;
    return counts;
}, {}).value();

=> {lumberjack : 2, all : 4, night : 2 ... }

 

Below is the complete list of functions provided by this library.  

 

Collections

Arrays

Functions

Objects

Utility

Chaining

each first bind keys noConflict chain
map initial bindAll values identity value
reduce last memoize functions times  
reduceRight rest delay extend mixin  
find compact defer pick uniqueId  
filter flatten throttle defaults escape  
reject without debounce clone result  
all union once tap template  
any intersection after has    
include difference wrap isEqual    
invoke uniq compose isEmpty    
pluck zip   isElement    
max indexOf   isArray    
min lastIndexOf   isObject    
sortBy range   isArguments    
groupBy     isFunction    
sortedIndex     isString    
shuffle     isNumber    
toArray     isFinite    
size     isBoolean    
      isDate    
      isRegExp    
      isNaN    
      isNull    
      isUndefined    

 

 

Date JS 

This is very fluent JS library for date and really easy to use.

 

date comparison

var temp = new Date();
temp.setHours(0);
temp.setMinutes(0);
temp.setSeconds(0);
temp.setMilliseconds(0);
 
var today = new Date(someDate.getTime()); 
var today.setHours(0);
var today.setMinutes(0);
var today.setSeconds(0);
var today.setMilliseconds(0);
 
(today == temp); // true|false

 

date comparison with date JS

/ with Datejs, but without .same
someDate.clone().clearTime().equals(Date.today());
 
// New
someDate.same().day();
 
// Or,
someDate.is().today();

 

more example

var today = Date.today();
var past = Date.today().add(-6).days();
var future = Date.today().add(6).days();


Date.compare(today, future);                    // -1
Date.compare(today, new Date().clearTime());    // 0
Date.compare(today, past)                       // 1

 

Date formatting [formatting options]

new Date().toISOString();  // ""2008-04-13T10:07:15Z""

new Date().toString("yyyy-MM-ddTHH:mm:ssZ");  // "2008-04-13T04:11:05Z"

Date.today().toString();           // native .toString() functionality

Date.today().toString("M/d/yyyy"); // 11/19/2007

Date.today().toString("d-MMM-yyyy"); // 19-Nov-2007

new Date().toString("HH:mm");      // 18:45

 

Please check this wiki page for more information about this library.

Popular posts from this blog

ERROR: Ignored call to 'alert()'. The document is sandboxed, and the 'allow-modals' keyword is not set.

Recently I found this issue while writing code snippet in "JSFiddle". And after searching, found this was happening because of new feature added in "Chrome 46+". But at the same time Chrome doesn't have support for "allow-modals" property in "sandbox" attribute.

Chromium issue for above behavior:
https://codereview.chromium.org/1126253007

To make it work you have to add "allow-scripts allow-modals" in "sandbox" attribute, and use "window.alert" instead of "alert".



<!-- Sandbox frame will execute javascript and show modal dialogs --> <iframe sandbox="allow-scripts allow-modals" src="iframe.html"> </iframe>


Feature added: Block modal dialog inside a sandboxed iframe.
Link: https://www.chromestatus.com/feature/4747009953103872

Feature working Demo page:
https://googlechrome.github.io/samples/block-modal-dialogs-sandboxed-iframe/index.html



CSS Specificity

Many time different CSS rules overlap on one or more element. And some people always get confuse about, which rule will take higher priority then other and why? CSS Specificity is the answer of all these kind of questions.
As the name suggest, the CSS rule which is more specific to the element will take higher priority then other. Means something like “#some_id{}” will always take higher priority then “*{}” universal selector.  And if duplicate rules are define then the last rule will be applied to the element.

The following list of selectors is by increasing specificity:
Type selector (e.g., div) and pseudo-elements in selector (e.g., :after) Class selectors (e.g., .some_class), attributes selectors (e.g., [type=”radio”]) and pseudo-class selector (e.g., :hover) Id selectors (e.g., #some_id)


ID takes higher priority then Class, Type and Universal selector (Note: Universal selector has no effect on specificity, see below special conditions). 



If duplicate rules are given, then last…

Guava: Some useful IO utilities

Guava IO package provides very useful utility classes for input/ouput stream, byte stream, file handling and many more. Here are few example which show case how these utilities can make your code much cleaner, modular and more readable.Copy “InputStream” to “OutputStream InputStream is = CopyStreams.class.getResourceAsStream("test.txt"); OutputStream os = System.out; ByteStreams.copy(is, os);Changing InputStream to “byte[]” InputStream is = CopyStreams.class.getResourceAsStream("test.txt"); byte[] isBytes = ByteStreams.toByteArray(is); // Now if you want to get base64 encoded string then it will be like this String isBase64Str = new sun.misc.BASE64Encoder().encode(isBytes);Combining two files in one File input1 = new File("c:\\testio\\AWords.txt"); File input2 = new File("c:\\testio\\BWords.txt"); File output = new File("c:\\testio\\ABWords.txt"); …