HexagonJS
Edit Page
Util
A collection of utility functions for manipulating arrays, objects and doing checks on types of variables.
Examples
Api
Properties
hx.versionString
The version property to allow easy identification of what hexagon version is in use.
Functions
hx.merge.definedobjects...ObjectObjectdeprecated
Deprecated
Replaced by hx.mergeDefined
Merges multiple objects together, only copying across defined values and returns the result as a new object.
The objects will be merged recursively, and arrays will be cloned. Any object that is not a plain object (see the isPlainObject function) will be replaced with an empty object {}.
// returns {'a': 1, 'b': 3}
hx.merge.defined({'a': 1}, {'a': undefined}, {'b': 3})

// returns {a: {b: 2, c: {d: 4, e: 'value'}}}
hx.merge.defined({a: {b: 2, c: {d: 3}}}, {a: {b: undefined, c: {d: 4, e: 'value'}}})
Arguments
objects...
The objects to combine
Returns
Object
The combined object
hx.parseHTMLhtmlStringDocumentFragmentdeprecated
Deprecated
The html method for selections has been removed to prevent XSS attacks.
A function for parsing a string to a DocumentFragment. Note: any script tags in the html string will be executed immediately - if you do not want this to happen, sanitize the string before passing into this function or remove the script tags from the document fragment created.
Arguments
htmlString
The html string to parse
Returns
DocumentFragment
A document fragment containing the parsed html.
hx.shallowMerge.definedobjects...ObjectObjectdeprecated
Deprecated
Replaced by hx.shallowMergeDefined
Merges multiple objects together where the first level of references are copied provided they are defined values (not undefined), and returns the result as a new object.
// returns {'a': 1, 'b': 3}
hx.shallowMerge.defined({'a': 1}, {'a': undefined}, {'b': 3})

// returns {a: {b: undefined, c: {d: 4, e: "value" }}}
hx.shallowMerge.defined({a: {b: 2, c: {d: 3}}}, {a: {b: undefined, c: {d: 4, e: 'value'}}})
Arguments
objects...
The objects to combine
Returns
Object
The combined object
hx.argmaxarrayArraylookupFunctionNumber
A function for getting the index of the item in an array with the highest value
Arguments
arrayArray
The array to find the max value of
lookupvalueAnyNumber
The function to use to lookup the value of an argument
Arguments
valueAny
An item in the array
Returns
The value of the argument in the array
Returns
The index of the item in the array with the lowest value
hx.argminarrayArraylookupFunctionNumber
A function for getting the index of the item in an array with the lowest value
Arguments
arrayArray
The array to find the min value of
lookupvalueAnyNumber
The function to use to lookup the value of an argument
Arguments
valueAny
An item in the array
Returns
The value of the argument in the array
Returns
The index of the item in the array with the lowest value
hx.checkParentsnodeHTMLElementcheckFunctionreturnArrayBoolean
A function for checking a node and it's parents for properties or contents.
This function will return the first non-undefined result by default or an array of all the non-undefined results if returnArray is true.
Arguments
nodeHTMLElement
The node to start checking from
checknodeHTMLElement
The check to run
Arguments
nodeHTMLElement
The current node being checked
returnArrayBoolean
If this value is true, the check will run all the way until the document element and return all the non-undefined results as an array.
Default: false
hx.clampminNumbermaxNumbervalueNumberNumber
Restricts a value to an interval
hx.clamp(0, 100, 105) // returns 100
hx.clamp(0, 100, -50) // returns 0
hx.clamp(0, 100, 75)  // returns 75
Arguments
The minimum value the result can take
The maximum value the result can take
valueNumber
The number to clamp
Returns
The value, clamped to the range [min, max]
hx.clampUnitvalueNumberNumber
Restricts a value to the unit interval [0, 1]
hx.clampUnit(0.15) // returns 0.15
hx.clampUnit(-0.1) // returns 0
hx.clampUnit(2.5)  // returns 1
Arguments
valueNumber
The number to clamp
Returns
The value, clamped to the range [0, 1]
hx.cleanNoderecurseBooleannode
A function for removing whitespace only nodes from a node. Useful when using multiline strings to generate html using hx.parseHTML
nodeHTMLElement
The node to clean
Arguments
recurseBoolean
Whether to recursively clean child nodes
Default: true
Returns
node
The cleaned node.
hx.cloneobjectObject / ArrayObject / Array
Clones an object or array. Items in arrays will also be cloned.
Arguments
objectObject / Array
The object/array to clone
Returns
The cloned object/array
hx.consoleWarningmessageStringmessages...String
Logs a hexagon warning to the console (with a stack trace)
Arguments
messageString
The message to display
messages...String
Additional messages to display.
hx.cyclearrayArray[Number]indexNumberNumber
Provides a way to access an array where the index loops round
hx.cycle([0, 1, 2], 0); // returns 0
hx.cycle([0, 2, 4], 1); // returns 2
hx.cycle([0, 2, 4], 2); // returns 4
hx.cycle([0, 2, 4], 3); // returns 0
hx.cycle([0, 2, 4], 4); // returns 2
hx.cycle([0, 2, 4], 5); // returns 4

hx.cycle([0, 2, 4], 400); // returns 2
Arguments
The array to cycle over
indexNumber
The index to access
Returns
The value at (index % array.length)
hx.debouncedurationNumberfnFunction
A function that prevents multiple calls to a function from being called in quick succession.
This is useful for calling an event when a user is inputting data, such as typing in an input field, to prevent a callback being run for every character entered.
Arguments
durationNumber
The duration to wait in milliseconds before making a function call.
fn
The function to call.
hx.definedvalueAnyBoolean
Checks if a value is defined
hx.defined(123)       // true
hx.defined([])        // true
hx.defined({})        // true
hx.defined(undefined) // false
hx.defined(null)      // false
Arguments
valueAny
The value to check
Returns
False if the value is undefined or null .
hx.deprecatedWarningnameStringalternative...String
Logs a hexagon deprecation warning to the console (with a stack trace)
Arguments
nameString
Name of the deprecated thing
alternative...String
A description of the alternative that should be used.
hx.endsWithvalueStringsuffixStringBoolean
Returns true if a string ends with a value
hx.endsWith('some-string', 'ing')  // returns true
hx.endsWith('some-string', 'some') // returns false
hx.endsWith('some-string', '')     // returns true
Arguments
valueString
The string to check against
suffixString
The suffix to check for
Returns
True if the value ends with suffix, otherwise false.
hx.findarrayArray[Any]indictorFunctionAny
Finds an item in an array using an indicator function. Returns the first match
// returns {v: 3}
hx.find([{v: 7}, {v: 6}, {v: 3}, {v: 5}], function(d){
  return d.v === 3;
});
Arguments
arrayArray[Any]
The array to hash onto
indictoritemAnyBoolean
The indicator function
Arguments
itemAny
An item from the array
Returns
True if the item is the one you are looking for, false if not.
Returns
Any
The item found in the array. Returns undefined if no match was found.
hx.flattenlistArrayArray
Flattens a 2D array into a 1D array.
//returns [1, 2, 3, 4, 5, 6]
hx.flatten([[1, 2], [3, 4], [5, 6]])
Arguments
listArray
A 2D array.
Returns
hx.groupByarrayArrayclassifierFunctionArray
Groups items in an array according to some classifier function.
var items = [
  { type: 'a', value: 1 },
  { type: 'a', value: 2 },
  { type: 'b', value: 3 },
  { type: 'b', value: 4 },
  { type: 'b', value: 5 },
  { type: 'c', value: 6 }
]

/* returns
  [
    [
      "a", [
        { type: 'a', value: 1 },
        { type: 'a', value: 2 }
      ]
    ],
    [
      "b", [
        { type: 'b', value: 3 },
        { type: 'b', value: 4 },
        { type: 'b', value: 5 }
      ]
    ],
    [
      "c", [
        { type: 'c', value: 6 }
      ]
    ]
  ]
*/
hx.groupBy(items, function(v){
  return v.type;
})
Arguments
arrayArray
An array of any type
classifieritemAnyAny
A function that returns the category that an item should be grouped into
Arguments
itemAny
The item to classify
Returns
Any
The category to group the item into
Returns
An array of tuples where the first element of each tuple is the category, and the second element is an array of grouped values
hx.hashstrStringmaxIntegerNumber
Hashes a string to an integer
// returns a number
hx.hash('some-string');

// calling it again with the same input will give the same result
hx.hash('some-string');

// returns an integer in the range [0, 5). So this could return 0, 1, 2, 3 or 4
hx.hash('some-string', 5);
Arguments
The string to hash
maxInteger
The maximum value the hash should take. You can leave this undefined
Returns
hx.hashListarrayArray[Any]indexStringAny
Hashes a string onto an item in a list
// returns a value from the list - for the same string, the value returned will always be the same
hx.hashList([0, 1, 2], "some-string");
Arguments
arrayArray[Any]
The array to hash onto
indexString
The string to hash
Returns
Any
The item retrieved from the array
hx.identityitemAnyitemAny
A function for returning the passed in value, useful for overriding formatters or as a default formatter.
Arguments
itemAny
The item to return.
Returns
itemAny
The passed in item.
hx.isArrayvalueAnyBoolean
Returns true if the value passed in is an array
hx.isArray("i am a string")                 // returns false
hx.isArray({})                              // returns false
hx.isArray(document.createElement('div'))   // returns false
hx.isArray([])                              // returns true
hx.isArray(123)                             // returns false
hx.isArray(function(){})                    // returns false
Arguments
valueAny
The value to check
Returns
True if the value is a array. False if not
hx.isBooleanvalueAnyBoolean
Returns true if the value passed in is a boolean
hx.isBoolean("i am a string")                // returns false
hx.isBoolean({})                             // returns false
hx.isBoolean(document.createElement('div'))  // returns false
hx.isBoolean([])                             // returns false
hx.isBoolean(123)                            // returns false
hx.isBoolean(function(){})                   // returns false
hx.isBoolean(true)                           // returns true
hx.isBoolean(false)                          // returns true
Arguments
valueAny
The value to check
Returns
True if the value is a boolean. False if not
hx.isFunctionvalueAnyBoolean
Returns true if the value passed in is a function
hx.isFunction("i am a string")                // returns false
hx.isFunction({})                             // returns false
hx.isFunction(document.createElement('div'))  // returns false
hx.isFunction([])                             // returns false
hx.isFunction(123)                            // returns false
hx.isFunction(function(){})                   // returns true
Arguments
valueAny
The value to check
Returns
True if the value is a function. False if not
hx.isNumbervalueAnyBoolean
Arguments
valueAny
The value to check
Returns
Whether the value passed in is a Number
hx.isObjectvalueAnyBoolean
Returns true if the value passed in is an object
hx.isObject("i am a string")                // returns false
hx.isObject({})                             // returns true
hx.isObject(document.createElement('div'))  // returns true
hx.isObject([])                             // returns false
hx.isObject(123)                            // returns false
hx.isObject(function(){})                   // returns false
Arguments
valueAny
The value to check
Returns
True if the value is a object. False if not
hx.isPlainObjectvalueAnyBoolean
Returns true if the value passed in is a plain object, where a plain objects is defined as:
  • Anything created with new (or equivalent)
  • DOM nodes
  • window
hx.isPlainObject("i am a string")                // returns false
hx.isPlainObject({})                             // returns true
hx.isPlainObject(document.createElement('div'))  // returns false
hx.isPlainObject([])                             // returns false
hx.isPlainObject(123)                            // returns false
hx.isPlainObject(function(){})                   // returns false
Arguments
valueAny
The value to check
Returns
True if the value is a plain object. False if not
hx.isStringvalueAnyBoolean
Returns true if the value passed in is a string
hx.isString("i am a string")                // returns true
hx.isString({})                             // returns false
hx.isString(document.createElement('div'))  // returns false
hx.isString([])                             // returns false
hx.isString(123)                            // returns false
hx.isString(function(){})                   // returns false
Arguments
valueAny
The value to check
Returns
True if the value is a string. False if not
hx.maxarrayArrayNumber
Returns the maximum value in the array
hx.max([7, 6, 3, 5]) // returns 7
Arguments
arrayArray
An array of numbers
Returns
The maximum value in the array
hx.maxByarrayArraylookupFunctionAny
Returns the maximum value in the array according to a extracted or computed value
// returns {v: 7}
hx.max([{v: 7}, {v: 6}, {v: 3}, {v: 5}], function(d){
  return d.v;
})
Arguments
arrayArray
An array of any type
lookupvalueAnyNumber
A function which extracts or computes the value to be compared
Arguments
valueAny
An item from the array
Returns
The number to compare by
Returns
Any
The item with the corresponding maximum value
hx.mergeobjects...ObjectObject
Merges multiple objects together, and returns the result as a new object.
The objects will be merged recursively, and arrays will be cloned. Any object that is not a plain object (see the isPlainObject function) will be replaced with an empty object {}.
// returns {'a': 2, 'b': 3}
hx.merge({'a': 1}, {'a': 2}, {'b': 3})

// returns {a: {b: 'hello', c: {d: 4, e: 'value'}}}
hx.merge({a: {b: 2, c: {d: 3}}}, {a: {b: 'hello', c: {d: 4, e: 'value'}}})
Arguments
objects...
The objects to combine
Returns
Object
The combined object
hx.mergeDefinedobjects...ObjectObject
Merges multiple objects together, only copying across defined values and returns the result as a new object.
The objects will be merged recursively, and arrays will be cloned. Any object that is not a plain object (see the isPlainObject function) will be replaced with an empty object {}.
// returns {'a': 1, 'b': 3}
hx.mergeDefined({'a': 1}, {'a': undefined}, {'b': 3})

// returns {a: {b: 2, c: {d: 4, e: 'value'}}}
hx.mergeDefined({a: {b: 2, c: {d: 3}}}, {a: {b: undefined, c: {d: 4, e: 'value'}}})
Arguments
objects...
The objects to combine
Returns
Object
The combined object
hx.minarrayArrayNumber
Returns the minimum value in the array
hx.min([7, 6, 3, 5]) // returns 3
Arguments
arrayArray
An array of numbers
Returns
The minimum value in the array
hx.minByarrayArraylookupFunctionAny
Returns the minimum value in the array according to a extracted or computed value
// returns {v: 3}
hx.min([{v: 7}, {v: 6}, {v: 3}, {v: 5}], function(d){
  return d.v;
})
Arguments
arrayArray
An array of any type
lookupvalueAnyNumber
A function which extracts or computes the value to be compared
Arguments
valueAny
An item from the array
Returns
The number to compare by
Returns
Any
The item with the corresponding minimum value
hx.parentZIndexnodeHTMLElementfindMaxBoolean
A function for checking a node's parents to find the first element with a z-index.
Arguments
nodeHTMLElement
The node to start checking from
findMaxBoolean
If this value is true, the maximum z-index from all the parents (up to the document element) will be returned.
Default: false
hx.randomIdlengthNumberalphabetStringNumber
Returns a random string using the length and alphabet provided
hx.randomId() // returns a 16-character hex string
hx.randomId(24) // returns a 24-character hex string
hx.randomId(10, 'abc') // returns a 10-character string using the letters a, b and c
Arguments
lengthNumber
The length of the string to generate
Default: 16
alphabetString
The alphabet to use. Defaults to hex
Default: ABCEDEF0123456789
Returns
The value, clamped to the range [0, 1]
hx.rangelengthNumberArray
Creates an array of values from 0 - length.
//returns [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
hx.range(10);
Arguments
lengthNumber
The length of the array to create.
Returns
hx.scrollbarSizeNumber
A method for getting the offset amount of the scrollbars in the current browser.
Different browsers implement scrollbars in different ways, with some changing the content size. This method returns the offset amount to allow for any structural changes that need to be made reliably across browsers.
Returns
The width of the browser scrollbars.
hx.shallowCloneobjectObject / ArrayObject / Array
Clones an object or array. Only the first level of values in the objects will be copied - this function will not recursively clone items - meaning references will be copied.
Arguments
objectObject / Array
The object/array to clone
Returns
The cloned object/array
hx.shallowMergeobjects...ObjectObject
Merges multiple objects together where the first level of references are copied, and returns the result as a new object.
// returns {'a': 2, 'b': 3}
hx.shallowMerge({'a': 1}, {'a': 2}, {'b': 3})

// returns {a: {b: 'hello', c: {d: 4, e: 'value'}}}
hx.shallowMerge({a: {b: 2, c: {d: 3}}}, {a: {b: 'hello', c: {d: 4, e: 'value'}}})
Arguments
objects...
The objects to combine
Returns
Object
The combined object
hx.shallowMergeDefinedobjects...ObjectObject
Merges multiple objects together where the first level of references are copied provided they are defined values (not undefined), and returns the result as a new object.
// returns {'a': 1, 'b': 3}
hx.shallowMergeDefined({'a': 1}, {'a': undefined}, {'b': 3})

// returns {a: {b: undefined, c: {d: 4, e: "value" }}}
hx.shallowMergeDefined({a: {b: 2, c: {d: 3}}}, {a: {b: undefined, c: {d: 4, e: 'value'}}})
Arguments
objects...
The objects to combine
Returns
Object
The combined object
hx.startsWithvalueStringprefixStringBoolean
Returns true if a string starts with a value
hx.startsWith('some-string', 'ing')  // returns false
hx.startsWith('some-string', 'some') // returns true
hx.startsWith('some-string', '')     // returns true
Arguments
valueString
The string to check against
prefixString
The prefix to check for
Returns
True if the value starts with prefix, otherwise false.
hx.sumarrayArray[Number]Number
Calculates the sum of an array
//returns 45
hx.sum([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
Arguments
The array to sum
Returns
The resulting summed value
hx.supportsnameStringBoolean
Provides a way to find out if the browser supports a feature.
Arguments
nameString
The name of the feature to check
// this is the list of checks that are currently available
hx.supports('touch') // touch events
hx.supports('date')  // date input type
Returns
True if the feature is supported
hx.transposedataArray[Array]Array[Array]
Flips a 2D array so that result[j][i] = data[i][j] . The result is returned as a new array.
// returns [[1, 4], [2, 5], [3, 6]]
hx.transpose([[1, 2, 3], [4, 5, 6]]);
Arguments
A 2D array
Returns
hx.tweenstartNumberendNumberalphaNumberNumber
Interpolates a value using linear interpolation
hx.tween(0, 5, 0.5)  // returns 2.5
hx.tween(0, 5, 0.1)  // returns 0.5
hx.tween(1, 5, 0)    // returns 0
hx.tween(1, 5, 1)    // returns 5
Arguments
startNumber
The start value
The end value
alphaNumber
The amount to mix the values by. Usually a value between 0 and 1.
Returns
The interpolated value
hx.uniquelistArrayArray
Returns a copy of the list supplied with duplicates removed
//returns [1, 2, 3]
hx.unique([1, 2, 1, 3, 3, 2, 2, 1, 3])
Arguments
listArray
The list, from which a copy will be created with only unique values.
Returns
A copy of the list supplied with duplicates removed
hx.ziparraysArray[Array]Array[Array]
Combines multiple arrays, so that the first element is an array containing all the first elements from the arrays provided, the second element is another array with all the second elements from the arrays provided, and so on.
// returns [[1, 4], [2, 5], [3, 6]]
var result = hx.zip([[1, 2, 3], [4, 5, 6]]);
Arguments
arraysArray[Array]
The arrays that should be zipped together.
Returns
The arrays that have been zipped together.