Skip to content
Jeffrey Heer edited this page May 15, 2015 · 22 revisions

WikiAPI ReferenceUtilities

Utilities

Type Checkers

# dl.isObject(value)

Checks if value is an Object.

# dl.isFunction(value)

Checks if value is a Function.

# dl.isString(value)

Checks if value is a String.

# dl.isArray(value)

Checks if value is an Array.

# dl.isNumber(value)

Checks if value is a Number or a String that parses to a number.

# dl.isBoolean(value)

Checks if value is a Boolean.

# dl.isDate(value)

Checks if value is a Date.

# dl.isValid(value)

Checks if value is not null, undefined or NaN.

# dl.isBuffer(value)

Checks if value is a Buffer instance.

Type Conversion

# dl.number(value)

Coerce value to a Number, ignoring nulls.

# dl.boolean(value)

Coerce value to a Boolean, ignoring nulls.

# dl.date(value)

Coerce (parse) value to a Date, ignoring nulls.

# dl.array(value)

If value is an array or null, returns it as-is. Otherwise, returns the single-element array [value].

# dl.str(value)

Coerce value to a JSON-style string with quotation characters escaped as needed.

Object Helpers

# dl.duplicate(value)

Creates a deep duplicate of an object. Internally, this method round-trips the value through JSON.stringify and JSON.parse. As a result, non-JSON-serializable values (for example, Function objects) are not duplicated.

# dl.equal(a, b)

Checks if a and b are deeply equal. Internally, this method calls JSON.stringify and compares the resulting strings. As a result, any non-JSON-serializable values will not be compared.

# dl.extend(object[, a, b, …])

Extend object by copying (in order) the properties of all other input objects.

# dl.keys(object)

Extract and return an array of object's keys. All properties of object, including those defined up the prototype chain, will be returned.

# dl.vals(object)

Extract and return an array of an object's values. Values for all properties of object, including those defined up the prototype chain, will be returned.

# dl.toMap(array)

Generate a boolean map object for array.

dl.toMap([1, 2, 3, 'a', 1]); // {'1': 1, '2': 1, '3': 1, 'a': 1}

Object Properties

# dl.field(string)

Parse a string property descriptor (e.g., "foo.bar") to an array.

dl.field("foo.bar.baz"); // ['foo', 'bar', 'baz']

# dl.accessor(field)

Parse a field property descriptor and return a corresponding accessor (getter) function. If field is a function or is null, it is returned as-is. Otherwise, field is parsed using dl.field and the result is used to create an accessor function that returns the field value for an input object.

dl.accessor('foo')({foo: 1, bar: 2}); // 1

# dl.$(field)

Shorthand for dl.accessor.

dl.$('foo')({foo: 1, bar: 2}); // 1

# dl.mutator(field)

Parse a field property descriptor and return a corresponding mutator (setter) function. The argument field is parsed using dl.field and the result is used to create a mutator function that updates the field value for an input object.

var obj = {foo: 1, bar: 2};
dl.mutator('foo')(obj, 3);
obj.foo === 3; // true

# dl.$length(field)

Create an accessor that extracts the length of String or Array values.

# dl.$year(field)

Create an accessor that extracts the year from Date values.

# dl.$month(field)

Create an accessor that extracts the month from Date values.

# dl.$date(field)

Create an accessor that extracts the date (day of the month) from Date values.

# dl.$day(field)

Create an accessor that extracts the day of the week from Date values.

# dl.$hour(field)

Create an accessor that extracts the hour from Date values.

# dl.$minute(field)

Create an accessor that extracts the minute from Date values.

Sorting

# dl.comparator(sortby)

Given either a string or array of strings as input, return a comparator function (suitable for use by Array.sort) that sorts values according to the given fields. The argument sortby can be either a single string or an array of strings. Each string value should indicate an object property to sort by. In addition, each string value may be prepended by '+' (to indicate ascending order, the default) or '-' (to indicate descending order).

var list = [{a:3, b:2}, {a:1, b:4}, {a:2, b:2}];
list.sort(dl.comparator('a')); // [{a:1, b:4}, {a:2, b:2}, {a:3, b:2}];
list.sort(dl.comparator(['+b', '-a'])); // [{a:3, b:2}, {a:2, b:2}, {a:1, b:4}];

# dl.cmp(a, b)

A default comparison function that sorts data in natural order.

# dl.numcmp(a, b)

A default comparison function for numerical data.

# dl.stablesort(array, sortby, key)

An alternative sorting method with guaranteed stable ordering. Sorts the input array using the comparator function sortby. In the case of ties, elements are compared using their original index in the array. The required key function argument should return a unique key value for each object.

Strings

# dl.keystr(values)

Map the values array to a string to use as a hash key.

# dl.startsWith(string, prefix)

Checks if string starts with the given prefix.

# dl.truncate(string, length[, position, word, ellipsis])

Truncate string such that it is no more than length characters long. The optional argument position indicates if the string should be truncated (have text removed) from the 'left', 'right' or 'center'. If true, the word argument indicates that the method should attempt to truncate to word boundaries, even if this results in a string shorter than length. The ellipsis argument indicates the string that should be used for missing text; the default is (Unicode U+2606).

dl.truncate('123456789', 5, 'right');   // '1234…'
dl.truncate('123456789', 5, 'left');    // '…6789'
dl.truncate('123456789', 5, 'center');  // '12…89'

# dl.template(text)

Generates and returns a string template function for data objects. The input argument text provides a string template. Within the template, variables may be included as {{foo}}, which is later replaced with the foo property of an input data object.

In addition, template variables support a number of filters for text transformation. Filters are specified within a template variable using a pipe-delimited syntax ({{property | filter1 | filter2 }}). Some filters may take one or more arguments ({{property | filter:arg1,arg2 }}). The available filters are:

  • length - return the length of a string.
  • lower - maps a string to lowercase (calls String.toLowerCase()).
  • upper - maps a string to uppercase (calls String.toUpperCase()).
  • lower-locale - maps a string to lowercase (calls String.toLocaleLowerCase()).
  • upper-locale - maps a string to uppercase (calls String.toLocaleUpperCase()).
  • trim - remove whitespace at the beginning and end of a string (calls String.trim()).
  • left:n - returns the n left-most characters of a string.
  • right:n - returns the n right-most characters of a string.
  • mid:n - returns the n central characters of a string.
  • slice:a,b - returns a substring according to String.slice(a, b).
  • truncate:n,pos - truncates the string using dl.truncate with the provided length (n) and an optional position argument (pos).
  • number:fmt - formats the string as a number using the provided format (fmt) string. The filter uses D3's formatting utilities and accepts a valid D3 number format pattern.
  • time:fmt - formats the string as a date/time using the provided format (fmt) string. The filter uses D3's time formatting utilities and accepts a valid D3 time format pattern.
var t = dl.template("Hi {{name}}, the day is {{stamp|time:'%A'}}.");
t({name: "Avery", stamp: new Date(2015, 4, 1)}); // Hi Avery, the day is Friday.

Miscellaneous

# dl.isNode

Boolean flag indicating if we are running server-side. This flag is set based on the existence of process.stderr in the global scope. In some cases this may not be a reliable indicator, so use with caution.

# dl.identity(value)

An identity function that simply returns the input value.

# dl.true()

Helper function that simply returns the value true.

# dl.false()

Helper function that simply returns the value false.

# dl.length(value)

Helper function that returns the length of a String or Array value.

Clone this wiki locally