npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ux-util

v0.10.0-alpha1

Published

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

Downloads

6

Readme

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.