tooly

javascript utility library covering everything from dom selection and css manipulation, object inheritance and extension, logging, event handling, string formatting, etc. Basically everything that I usually want/need at my fingertips for any given project. Compatible with node, amd, and modern browsers. Just under 4kb minified and gzipped (~3kb without the logger and timer modules, which shouldn't be used in production anyway - see dist/tooly-slim.js).

Install

$ npm install tooly

Documentation

lokua.github.io/tooly

Custom Build

You can create a custom build of particular categories.

cd path_to/node_modules/tooly
# from the tooly module root, install dev dependecies
npm install
# run the script and `include` command
# passing as arguments modules you want included 
# this will also run related Grunt umd and uglify tasks
node bin/build include logger timer string
# run the `grunt build` task to wrap tooly in umd, minify etc.
grunt build

Available categories include:

By default the custom build will be located at ./dist/tooly-custom.js, or alternatively, you can specify a custom output file during the build instruction:

node bin/build include dom string -o my-custom-tooly-build.js && grunt build

This should be preferred.

License

The MIT License (MIT)

© 2014 Joshua Kleckner

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

tooly .
each
(obj, iterator, context)    → {Object|Array}

Port of underscore's each. Falls back to native forEach for Arrays when available.
The iterator argument takes the following signature for Arrays:
iterator(value, index, array) where the array is the same collection passed
as the obj argument. For objects the signature is:
iterator(value, key, object).

parameters:
obj {Object|Array}

the collection to iterate over

iterator {Function}

the function called on each element in obj

context {Object}

the context, used as this in the callback

returns
{Object|Array}

obj

example:
var obj = {'1': 1, '2': 2, '3': 3, '4': 4};
each(obj, function(v, k, o) { o[k] = v*100; });
obj; //=> {'1': 100, '2': 200, '3': 300, '4': 400};

var arr = [1, 2, 3, 4];
each(arr, function(v, i, a) { a[i] = v*100; });
arr; //=> [100, 200, 300, 400];
tooly .
sort
(arr, key, dsc)    → {Array}

Alpha-numeric sort arrayof objects by key.
Numbers preceed letters regardless of being instances of Number or String.
Note that this method does modify the original array.

Example

var data = [
  {name: 'a'},{name: 2},{name: 1},
  {name: 'b'},{name: 'c'},{name: 'z'}
];
var ascending = tooly.sort(data, 'name');
//=> [{name: 1},{name: 2},{name: 'a'},{name: 'b'},{name: 'c'},{name: 'z'}]

// pass descending flag third arg
var descending = tooly.sort(data, 'name', true);
//=> [{name: 'z'},{name: 'c'},{name: 'b'},{name: 'a'},{name: 2},{name: 1}]
parameters:
arr {Array}

the array to sort

key {String}

the key to sort by

dsc {boolean}

sorts descending order if true

returns
{Array}

the original arr sorted.

tooly .
Frankie
(el, context)    → Frankie instance

The Frankie class - named after the late, great DJ Frankie Knuckles (one of the greatest)
selectors of all time ;). A micro DOM util with a jQuery-like API.
Keeps an internal reference to a selectAll query on the passed
el. Most methods will return the instance for chainability.

parameters:
el {String|HTMLElement}

valid css selector string, can contain multiple selectors separated my commas (see the example)

context {Mixed}

a parent context to search for the supplied el argument. can be any of the following:

  • HTMLElement
  • String
  • Array<HTMLElement>
  • NodeList
  • Frankie instance
example:
// alias the Frankie namespace
var $ = tooly.Frankie.bind(this);
var $divs = $(divs);
$divs.css({color:'green'});
// multiple yet separate selectors must be comma separated
$('div, p')
  .addClass('purple')
  .addClass('yellow')
  .removeClass('g')
  .css({'border-radius':'4px'})
  .prepend('<h1>---</h1>')
  .append('<h1>+++</h1>')
  .html('H T M L');
tooly.Frankie #
addClass
(klass)    → {tooly.Frankie}

add a css class to element

parameters:
klass {String|Array<String>}

the css class(es) to add

returns
{tooly.Frankie}

this

tooly.Frankie #
append
(content)    → {tooly.Frankie}

append content to all elements in the set of matched elements.

parameters:
content {mixed}

the content to append

returns
{tooly.Frankie}

this

tooly.Frankie #
attr
(attr, the)    → {Object}

get or set a(n) html attribute(s)

parameters:
attr {Object|String}

the attribute to get/set

the {String|Number}

value of the attribute attr (only if attr is a name string)

returns
{Object}

Frankie or the attribute value if only a single string is passed for the first argument

tooly.Frankie #
children
()    → {tooly.Frankie}

Create a new Frankie instance from all first-generation child elements of
the current set of matched elements;

TODO: try with Element.childNodes instead of children so we don't have
to do the array conversion
OR probably better to simple instantiate new Frankie
TODO: add filter

returns
{tooly.Frankie}

new Frankie instance

tooly.Frankie #
css
(styles)    → {tooly.Frankie}
parameters:
styles {String|Object}

either a single comma separated key value pair of strings, or object hash

returns
{tooly.Frankie}

this

example:
// as key val pair (key must also be a string)
var el = tooly.select('#main');
$('div').css('background', 'red');

// or as hash (notice that hyphenated keys must be quoted)<br>
$('div').css({ width: '100px', background: 'red', 'font-size': '24px' });

// also can take valid css selector string in place of element
// below will match the document's first div
$('div').css('border', '2px solid red');
tooly.Frankie #
empty
()    → {tooly.Frankie}

remove all child nodes from the set of matched elements.
TODO: remove listeners?

returns
{tooly.Frankie}

this

tooly.Frankie #
eq
(index)    → {tooly.Frankie}

Create a new instance of Frankie with only the element
specified by index

parameters:
index {Number}

the index of the element

returns
{tooly.Frankie}

new Frankie instance

tooly.Frankie #
get
()    → undefined

Get the element at index i from Frankie's selected elements.
Unlike #eq, get returns the actual HTMLElement.

tooly.Frankie #
hasClass
()    → undefined
tooly.Frankie #
html
(content)    → {String|Object}

fill each element in the set of matched elements with content.
Replaces existing content.
If called with 1 arg, the first matched element's innerHTML is returned.

parameters:
content {Mixed}
returns
{String|Object}

the first matched el's innerHTML or null when in get mode, otherwise this for chaining

tooly.Frankie #
on
(event, fn)    → {this}

Ultra simplified wrapper for addEventListener.
Does not currently support jQuery-style data passing

parameters:
event {String}

the event to listen to, like 'click'

fn {Function}

the handler to execute when event is fired

returns
{this}
tooly.Frankie #
parent
()    → {tooly.Frankie}

Create a Frankie instance from all parent elements of the set of matched elements.

returns
{tooly.Frankie}

a new Frankie instance

tooly.Frankie #
prepend
(content)    → {tooly.Frankie}

prepend content to all elements in the set of matched elements.

parameters:
content {mixed}

the content to prepend

returns
{tooly.Frankie}

this

tooly.Frankie #
remove
(element, returnRemoved)    → {this|Frankie}

// TODO

parameters:
element {mixed}

the element(s) to remove from the instance's array of elements as well as the DOM

returnRemoved {Boolean}

If true, the elements will be returned from the function (within) a new Frankie instance (which will keep them in memory if yo store them in a reference)

returns
{this|Frankie}
tooly.Frankie #
removeClass
(klass)    → {tooly.Frankie}

remove a css class from an element

parameters:
klass {String}

the css class(es) to remove

returns
{tooly.Frankie}

this

tooly.Frankie #
toggleClass
(klass)    → {this}
parameters:
klass {String}
returns
{this}
tooly.Frankie #
zilch
()    → {Boolean}
returns
{Boolean}

true if this instance's inner elements array is empty.

tooly .
Handler
(context)    → Handler instance

Class constructor. Simple event handling, best when inherited. Execute named functions
by triggering a Handler reference of the same name.

Example

var handler = new tooly.Handler();

function world() { 
  console.log('world!'); 
}

function hello() { 
  console.log('hello '); 
  handler.trigger('hello');
}

handler.on('hello', function() { 
  world(); 
});

hello(); //=> "hello world!";

Using #inherit, you can add all Handler functionality to your class
without having to use the handler reference:

function MyClass(name) {
  // initialize the parent class
  tooly.Handler.call(this);
  this.name = name;
  this.init();
  return this;
}

// add all of the tooly.Handler.prototype methods to MyClass.prototype.
// third argument also augments MyClass.prototype
tooly.inherit(MyClass, tooly.Handler, {

  init: function() {
    this.on('load', function() {
      console.log(this.name + ' loaded');
    });
  },

  load: function() {
    // whatever...
  }
});

var instance = new MyClass("let's drink a lot of Malort and get "); 
instance.load(); //=> "let's drink a lot of Malort and get loaded"
parameters:
context {Object}

(optional) designates the owner of the handlers array that holds all callbacks. When blank the Handler instance uses its own internal array. If you'd like to keep track of the handlers outside of the instance, pass a context such that context.handlers is an array.

tooly.Handler #
executeHandler
(fn)    → {this}

Executes all handlers attached to the named function.
For Handler#on(<name>) to work, <name> itself needs to call #executeHandler.

Example

var value = 0;
var handler = new tooly.Handler();

function inc() { 
  value += 10; 
  handler.executeHandler('inc');
}

function jump() {
  this.value *= 2;
}

handler.on('inc', announce);
inc();
value; //=> 20;
parameters:
fn {String|Object}

the name of the function that will announce to attached handlers

returns
{this}
alias:

#trigger

tooly.Handler #
on
(fn, handler)    → {Object}

Register an event handler for a named function.

parameters:
fn {(String|Function)}

the function that will call the handler when executed

handler {callback}

the handler that we be called by the named function

returns
{Object}

this for chaining

tooly.Handler #
registerCallbacks
(handlers)    → {this}

Add callbacks to the list of handlers. The callbacks must be an object collection of
key-value pairs where the identifier key is the name of a function that calls the
#executeHandler method with the same name as the key, while the value is the callback
function itself. This method should not be used if only registering a single callback,
for that use #on.

parameters:
handlers {Object}

collection of callback functions

returns
{this}
tooly.Handler #
remove
(fn)    → undefined

Remove all handler's attached to fn. All subsequent calls to
#executeHandler(fn) will no longer have an effect.

parameters:
fn {Function}

the named function that executes handler(s)

tooly.Handler #
removeAll
()    → undefined

Remove all handlers. Any subsequent call to #executeHandler will have no effect.

tooly.Handler #
trigger
()    → undefined

alias for #executeHandler

alias:

#executeHandler

tooly .
Logger
(name, options)    → Logger instance

Class constructor. Typical logging functionality that wraps around console.log
with css coloring and level control. The Logger level hierarchy is as follows:

  • -1: off
  • 0: log (no difference from console.log)
  • 1: trace
  • 2: debug
  • 3: info
  • 4: warn
  • 5: error

Only calls that are greater or equal to the current Logger.level will be run.

Format

Format strings follow the same usage as node.js or the web interface, depending
on what environment you are in.

  • node
    • %s, %j, and %d can be used for 'string', 'json', or 'number'
  • browser
    • %s or %o can be used in place of 'string' or 'object'

Example

var logger = new tooly.Logger('TEST_LOGGER', { level: 2 });
logger.trace(logger); // will not output

Options

  • level: number (default 2: debug)
  • bypassTimestamp: boolean (default: false)
  • bypassLine: boolean (remove line number from output prefix. default: false)
  • textFormat: a css for a %c flag, ie. 'color:blue;font-size:22px;'
  • lineFormat: same as textFormat for line number styling

All active loggers in the current context can be disabled, regardless of level,
by setting the static tooly.Logger.off = true. Setting back to false will resume
logging at each loggers previous level.

parameters:
name {String}

optional name to identify this instance. The name will preceed any output message

options {Object}

an object containing this logger's level and other output options

tooly .
construct
(ctor, args)    → {Object}
parameters:
ctor {Function}
args {Object|Array}
returns
{Object}
tooly .
extend
(dest, src)    → {Object}

Add the "own properties" of src to dest.
Used throughout the application to add prototype
methods to tooly classes without
assigning Object as their prototype.

parameters:
dest {Object}

the destination object

src {Object}

the source object

returns
{Object}

dest

tooly .
fromPrototype
(prototype, object)    → {Object}

Object literal assignment results in creating an an object with Object.prototype
as the prototype. This allows us to assign a different prototype while keeping
the convenience of literal declaration.

parameters:
prototype {Object}
object {Object}
returns
{Object}
author:

Yehuda Katz

tooly .
inherit
(parent, child, extend)    → undefined

Helper to perform prototypal inheritance.
Note that this method overwrites the child's original prototype.
Also note that the child's constructor needs to call parent.call(this)

parameters:
parent {Function}
child {Function}
extend {Mixed}

additional members to the Child's prototype

example:
function Parent() {}
Parent.prototype.b = 2;
function Child() { Parent.call(this); } // this is a must
tooly.inherit(Parent, Child, { a: 1 });
var child = new Child();
console.log(child.a + child.b); //=> 3
// for a more practical example see the tooly.Handler documentation.
tooly .
isFalsy
(obj)    → {Boolean}

Extensively check if obj is "falsy".

isFalsy returns true for the following:

var undefinedValue;
var nullValue             = null;
var setUndefined          = undefined;
var falseValue            = false;
var zero                  = 0;
var emptyString           = ''; // same for ' \n\t   \n'
var falseString           = 'false';
var zeroString            = '0';
var nullString            = 'null';
var undefinedString       = 'undefined';

Note that in the cases of falsy strings, the check is
done after a call to String.trim, so surrounding
whitespace is ignored:
isFalsy('\n\t false \n') //=> true

parameters:
obj {mixed}

the object to check

returns
{Boolean}

true if obj is "falsy"

alias:

#falsy

see:

#isTruthy

tooly .
isHash
(value)    → {Boolean}

port of is.hash

Test if value is a hash - a plain object literal.

parameters:
value {Mixed}

value to test

returns
{Boolean}

true if value is a hash, false otherwise

author:

Enrico Marino (with minor edits)

tooly .
isTruthy
(obj)    → {Boolean}

Opposite of isFalsy.

parameters:
obj {mixed}

the object to check

returns
{Boolean}

true if obj is "truthy"

alias:

#truthy

see:

#isFalsy

tooly .
scale
(n, oldMin, oldMax, min, max)    → {Number}

scale a number from one range to another

parameters:
n {Number}

the number to scale

oldMin {Number}
oldMax {Number}
min {Number}

the new min

max {Number}

the new max

returns
{Number}

the scaled number

tooly .
toType
(obj, klass)    → {String|Boolean}

A more useful alternative to the typeof operator.
If only the obj argument is passed, the class of that object is returned.
If the second argument klass is passed, a boolean indicating whether obj
is of class klass or not is returned.

parameters:
obj {Object}

the object

klass {String}

object class to compare to

returns
{String|Boolean}

the type of object if only obj is passed or true if obj is of class klass, false otherwise

alias:

type

author:

Angus Croll

tooly .
contains
(source, str, index)    → {Boolean}

minimal Function version of ECMAScript6 String.prototype.contains.

parameters:
source {String}

the source string

str {String}

the string to find

index {String}

[optional] index to start searching from

returns
{Boolean}

true if source contains str

tooly .
endsWith
(str, suffix)    → {Boolean}

minimal Function version of ECMAScript6 String.prototype.endsWith.

parameters:
str {String}

the string to check

suffix {String}

the "endWith" we are seeking

returns
{Boolean}

true if str ends with suffix

tooly .
extension
(str)    → {String}

get the extension of a file, url, or anything after the last . in a string.

parameters:
str {String}

the string

returns
{String}
tooly .
formatMoney
(n)    → {String}

Format money.

parameters:
n {Number|String}

a number or numerical string

returns
{String}

n formatted as money (comma separated every three digits)

example:
var loot = '$' + tooly.formatMoney(10989.34); 
loot //=> "$10,989.00"
see:

http://stackoverflow.com/a/14428340/2416000 (slightly modified to coerce string-numbers)

tooly .
formatString
(format)    → {String}

Function version of (C# style?) String.format

parameters:
format {String}

the format string

returns
{String}

the formatted string

example:
var formatted = tooly.format('{0}{1}', 'tooly', '.js')); 
formatted; //=> 'tooly.js'
alias:

#stringFormat

see:

#format

tooly .
formatTime
(time)    → {String}

Utility method to convert milliseconds into human readable time

parameters:
time {Number}

the time value in milliseconds

returns
{String}

time formatted as hh:mm:ss

tooly .
lPad
(v, len, symbol)    → {String}

left pad

parameters:
v {String}

the string to pad

len {Number}

the length such that len - v = number of padding chars

symbol {String}

the symbol to use for padding, defaults to single white space

returns
{String}

the left padded string

see:

tooly#rpad

tooly .
rPad
(v, len, symbol)    → {String}

right pad

parameters:
v {String}

the string to pad

len {Number}

the length such that len - v = number of padding chars

symbol {String}

the symbol to use for padding, defaults to single white space

returns
{String}

the right padded string

see:

tooly#lpad

tooly .
repeat
(str, n)    → {String}

Function version of ECMAScript6 String.prototype.repeat

parameters:
str {String}

the string to repeat

n {Number}

the number of times to repeat

returns
{String}

the string repeated, or an empty string if n is 0

tooly .
sliceRel
(url, preSlash, trailingSlash)    → {String}

Extracts final relative part of url, optionally keeping forward,
backward, or both slashes. By default both front and trailing slashes are removed

parameters:
url {String}

the url or filepath

preSlash {Boolean}

keeps slash before relative part if true

trailingSlash {Boolean}

keeps last slash after relative part if true, though does not add a trailing slash if it wasn't there to begin with

returns
{String}
tooly .
startsWith
(str, prefix)    → {Boolean}

minimal Function version of ECMAScript6 String.prototype.startsWith.

parameters:
str {String}

the string to check

prefix {String}

the "startsWith" we are seeking

returns
{Boolean}

true if str starts with prefix

tooly .
stripExtension
(str)    → {String}

Get a copy of str without file extension, or anything after the last .
(does not change the original string)

parameters:
str {String}

the string to copy and strip

returns
{String}

the copied string with file extension removed

tooly .
tag
(tag, attrs, asString)    → {HTMLElement|String}

Simple DOM element creation using jade-like syntax for the element
declaration and options hash for attributes. The attribute hash can take a content
argument for the element's innerHTML property, which itself can be another tag

Examples

tag('a'); //=> <a></a>
tag('a.link--plain') //=> <a class="link--plain"></a>
tag('a', 'MUSIC!!!') //=> <a>MUSIC!!!</a>
tag('a#main.link--plain', { rel: 'nofollow', href: 'music', content: 'MUSIC!!!' })
//=> <a href="music" rel="nofollow">MUSIC!!!</a>
tag('#main', tag('.sub')) //=> <div id="main"><div class="sub"></div></div>
parameters:
tag {String}

jade-like element declaration

attrs {Object}

options hash of attributes

asString {Boolean}

returns string representation instead of HTMLElement, defaults to false

returns
{HTMLElement|String}

element or string representation