ux-util

The JavaScript ux utility library for common methods equals, format, extend, isPlainObject that can work with or without jQuery

npm install ux-util
2 downloads in the last month

ux-util

  • version: 0.10.0-alpha1
  • status: in development

JavaScript utility library for common methods like equals, format, extend, isPlainObject, create, apply, isGlobal, that can work inside of multiple JavaScript ecmascript 5 environments.

Contents

Key Requirements

  • Runs in multiple JavaScript environments: browsers, web workers, nodejs, windows rt
  • AMD support
  • Custom builds thats allows users/developers to only import what they need for standalone libraries or projects.
  • Target ecmascript 5, but keep ecmascript 6 in mind
  • Supports other UX libraries

Rationale

These are key utility methods for various "ux" libraries. The goal for many of the libraries is to run in multiple environments. Creating a flexible core utilities library enables bundling methods for upstream libraries that need to consume utility methods without forcing the user to include unused methods.

Why not use jQuery or underscore?

jQuery is amazing, but it doesn't currenly run on node.js on windows or on node.js on other operating systems without other dependencies. jQuery is at least enabling AMD modules for jQuery 2.0. Underscore wasn't modular enough. Lo-dash is currently the closest to the goal of this library, but it was still missing functionality needed for ux libraries.

Special Thanks

Thanks to jQuery and opensource for making lives easier on everyone. The following methods are modified internals of jQuery that are made to run in multiple environments: extends, isWindow, isPlainObject.

Builds

The builds for nodejs, browser, and amd will let you include files as needed. The builds will also include a util.js file that includes all the methods bundled in a single file. The build process creates 3 versions of the scripts, one for CommonJS, one for AMD, and one with closures for the browser.

The source files are included with the npm module inside the src folder. This is so that developers and script consumers may cheery pick the functionality he/she wants and include the files as neede for custom builds.

To build and test everything use:

$ grunt ci

Browser Distribution

location: dist/browser

The browser distribution will use closures to wrap functionality and it uses the global variable of "ux.util". If you wish to use a method you can do the following:

    <script type="/scripts/ux-util/equals.js"> </script>
    var equals = self.ux.util.equals;
    if(equals(left, right))
    {
        // do something
    }

AMD Distribution

location: dist/amd[/lib]

The amd distribution has the main file in the root and the rest of the files are pushed into the lib folder. This is so that the same require statements will work with node and when using something like require js with a browser.

CommonJS Distribution

location: lib

The files are located inside of the lib folder.

API

apply

apply is similar to Function.prototype.apply, but invokes a direct function when there thisArg is not present, otherwise, it uses call, which is faster than apply in most cases.

based on findings from http://jsperf.com/function-calls-direct-vs-apply-vs-call-vs-bind

example
    var util = require('ux-util/lib/apply');

    var callback = function(data) {
        var copy = data;

        if(this.data) {
            for(var prop in this.data)
                copy[prop] = this.data[prop];
        }

        copy.status = "data has been retrieved";

        return copy;
    };

    var data = apply(callback, [{firstName: "nathan", lastName: "fillion"}]);

    if(data.self)
        console.log("self exists");
    else 
        console.log(data.status);

    var data2 = apply(callback, {self: true},  [{firstName: "nathan", lastName: "fillion"}]);

    if(data2.self)
        console.log("self exists");
    else 
        console.log(data2.status);

create

create dynamically creates an instance of a object by passing the array of arguments to the constructor.

example
    var util = require('ux-util/lib/create');

    var Person = function(first, last, middle) {
        this.firstName = first || "";
        this.lastName = last || "";
        this.middleName = middle || "";
    };

    var actor = create(Person, ["Alan", "Tudyk"]);

    console.log(actor.firstName);  // Alan
    console.log(actor.lastName);   // Tudyk
    console.log(actor.middleName); // ""

equals

equals will assert if two values or objects are equal to each other. If an object has an equals method, that method will be used to determine equality.

example
    var util = require('ux-util/lib/equals');

    var log = console.log;

    log(util.equals("one", "one"));     // true
    log(util.equals(["one"], ["one"])); // true
    log(util.equals(2, 3)); // false

    var Person = function(firstName, lastName, email) {
        this.firstName = firstName;
        this.lastName = email;
        this.email = email;
    };

    Person.prototype.equals = function(right) {
        if(right == null)
            return false;

        return (left.firstName === right.firstName &&
                left.lastName === left.lastName &&
                left.email === left.email);
    };

    var nathan = new Person("Nathan", "Fillion");
    nathan.meta = "awesomeness";

    var nathan2 = new Person("Nathan", "Fillion");

    console.log(util.equals(nathan, nathan2)); // true

extend

extend will merge functions and values from multiple objects into the target object using a deep copy if specified.

example
    var util = require("ux-util/lib/extend");

    var Animal = function() {
        this.type = "animal";
        this.sound = null;
        this.attack = 0.2;
    };

    var Fox = function() {
        Animal.call(this);
        this.type = "fox";
        this.sound = "what does the fox say?";
        this.att
    };

    util.inherit(Fox, Animal);

    var extensions = {
                           options: {
                               hp: 100,
                               mp: 50,
                               spells: ["burn"]
                           },
                           claw: function() { 
                               return this.attack * 12;
                           }
                       };

       util.extend(true, Fox.prototype, extensions, {
        tailAttack: function() {
            return this.attack * 20;
        }
       });

       var fox = new Fox();
       console.log(fox.options.spells === extensions.spells); // false, its a copy

format

format will inject values into placeholders of a string template. This is based upon .NET''s string.Format method.

example
    var util = require("ux-util/lib/format");

    var message = util.format("[{0}] - {1}", "#tag", 2);
    console.log(message); // [#tag] - 2


    // format.globalizeFormat must have a signature of  
    // function(value, format)

    // jQuery Globalize already uses this.
    util.format.globalizeFormat = Globalize.format;
    console.log(util.format("{0:n2}", 10.045234));
    console.log(util.format("{0:c}", 1.25));

globals

globals returns the global namespace. This variable can be used in all environments.

example

    var util = require('ux-util/lib/global');

    if(util.globals.window)
    {
        // browser environment
        var div = util.globals.document.createElement("div");
        console.log(div);
    }

    // create variable in the global namespace. 
    util.globals.ux = {};

href

href expands a relative url with a tilda prefix into the correct relative path. The function can also be bound create a localized version that has a different configuration.

example

    var util = require('ux-util/lib/href');

    util.href.url = "/app"
    var url = util.href("~/home/about");

    console.log(url); // "/app/home/about"

    var customHref = util.href.bind({url: "http://bob.com/"});
    var about = customHref("~/about");

    console.log(about); // "http://bob.com/about"

inherits

inherits will apply JavaScript inheritance to a subclass/function.

example
    var util = require('ux-util/lib/inherits');

    var Animal = function() {
        this.type ="animal";
        this.name = "";
    };

    var Dog = function() {
        Animal.call(this);
        this.name = "dog";
    };

    // Sub Class, Base Class, properties
    inherits(Dog, Animal, {test: {value: "test"}});

    var dog = new Dog();
    console.log(dog.name); // dog
    console.log(dog.test); // test
    console.log(dog instance of Dog); // true
    console.log(dog instance of Animal); // true

isGlobal

isGlobal determines if the instance is the global namespace. The global namespace varies depending on the environment.

  • browser: window
  • nodejs: global
  • web worker: self
  • other: this
example

    var util = require('ux-util/lib/global'),
        obj = {},
        obj2 = util.globals;

    console.log( util.isGlobal(obj) );  // false
    console.log( util.isGlobal(obj2) ); // true

isPlainObject

isPlainObject determines if an object is a vanilla JavaScript object. Based on jQuery's implementation.

example
    var util = require("ux-util/lib/is-plain-object");

    // if browser
    console.log(util.isPlainObject(window)); // false

    // if node
    console.log(util.isPlainObject(global)); // false

    console.log(util.isPlainObject({})); // true

isWindow

isWindow determines if the instance is the window object. This method is safe to use in the node environment.

example

    var util = require('ux-util/lib/global'),
        obj = {},
        obj2 = util.globals;

    console.log( util.isWindow(obj) );  // false
    console.log( util.isWindow(obj2) ); // true if this code is in the browser, otherwise false.

logFactory

logFactory is a singleton instance that finds or creates loggers based upon the specified type name. This is simlar to LogManager in log4x frameworks. This is meant to be more of a common.logging wrapper which defaults to using the console.

You can implement your own logging factory.

example
    var logManager = require("ux-util/lib/log-factory").logFactory;

    var logger = logManager.getLogger("util");
    if(logger.isDebugEnabled)
        logger.debug("here is the message");

    logManager.setFactory(new CustomLogFactory())

makeArray

makeArray transforms various values into an array.

  • null or undefined or zero => empty array
  • multiple arguments => [argument1, argument2, etc]
  • array like objects (i.e. arguments) => [argument1, argument2, etc]
  • HtmlCollection => [element1, element2, etc]
  • Iterator => [next1, next2, etc]
example

    var makeArray = require("ux-util/lib/make-array").makeArray;

    // Array Like
    var func = function() {
        var args = makeArray(arguments);
        return args.filter(function(o) { return typeof o === "string"; });
    };        

    var filtered = func("one", "two", 3);
    console.log(filtered); // ["one", "two"];

    // HtmlCollection
    var forms = makeArray(document.forms);
    console.log(forms);

    var function generator() {
        yield 1;
        yield 2;
    };

    // Iterator
    var values = makeArray(generator());
    console.log(values); // [1, 2];


    var arr = makeArray("one");
    console.log(arr); // ["one"];

mixin

mixin will merge functions and values from multiple objects into the target object using a shallow copy.

example
    var util = require("ux-util/lib/mixin");

    var Animal = function() {
        this.type = "animal";
        this.sound = null;
        this.attack = 0.2;
    };

    var Fox = function() {
        Animal.call(this);
        this.type = "fox";
        this.sound = "what does the fox say?";
        this.att
    };

    util.inherit(Fox, Animal);

    var spells = ["freeze"];
       util.mixin(Fox.prototype, {
           options: {
               spells: spells
           },
        claw: function() { 
            return this.attack * 12;
        }
    });

       var fox = new Fox();
       console.log(fox.sound);   // what does the fox say?
       console.log(fox.claw());  // 2.4
       console.log(fox.options.spells === spells); // true, because it is the same reference.

using

using is similar to the using method found in c#. Using will create an instance if the first argument is a function. The object will be disposed and destroyed after its use, even if it throws an error.

example
    var using = require("ux/lib/using");

    var Db = function() {

    };

    Db.prototype = {
        dispose: function() {

        },
        insert: function(entity) {

        },
        save: function() {

        }
    };


    using(Db, function(db) {
        db.insert({id: 1, name: "Serenity"});
        db.save();
    });

License

For extends, isPlainObject, isWindow: Copyright 2014 jQuery Foundation and other contributors http://jquery.com/

The MIT License (MIT)

Copyright (c) 2013-2014 Michael Herndon http://dev.michaelherndon.com

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.

npm loves you