Skip to content

DannyNemer/dantil

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

dantil

A Node.js utility library.

In addition to much original functionality, includes many improved alternatives to native functions.

Installation

npm install dannynemer/dantil

Usage

var dantil = require('dantil')

Utility

File System

Console

Profiling

Lang

Function

Object

Array

Number

String

“Utility” Methods

dantil.illFormedOpts(schema, [options], [ignoreUndefined])

#

Checks if options does not adhere to schema, thereby simulating static function arguments (i.e., type checking and arity). If ill-formed, prints descriptive, helpful errors (including the file-path + line-number of the offending function call).

Arguments

  1. schema (Object): The definition of required and optional properties for options.
  2. [options] (Object): The options object to check for conformity to schema.
  3. [ignoreUndefined] (Object): Specify ignoring non-required options properties defined as undefined. Otherwise, reports them as errors, which is useful for catching broken references.

Returns

(boolean): Returns true if options is ill-formed, else false.

Example

var mySchema = {
  // Optionally accept an `boolean` for 'silent'.
  silent: Boolean,
  // Optionally accept an `Array` of `string`s for 'args'.
  args: { type: Array, arrayType: String },
  // Require `string` 'modulePath'.
  modulePath: { type: String, required: true },
  // Optionally accept one of predefined values for 'stdio'.
  stdio: { values: [ 'pipe', 'ignore', 0, 1, 2 ] },
  // Optionally accept an `Object` that adheres to the nested `schema` object.
  options: { type: Object, schema: {
    cwd: String,
    uid: Number,
  } },
}

function myFork(options) {
  if (dantil.illFormedOpts(mySchema, options)) {
    // => Prints descriptive, helpful error message

    throw new Error('Ill-formed options')
  }

  // ...stuff...
}

The contents of foo.js:

myFork({ modulePath: './myModule.js', stdio: 'out' })

Output:
dantil.illFormedOpts() example output


dantil.tryCatchWrapper(func, [exitProcessIfFailure])

#

Invokes func within a try block, and catches and prints any thrown exceptions (including the stack trace if an Error is thrown).

Arguments

  1. func (Function): The function to invoke within a try block.
  2. [exitProcessIfFailure] (boolean): Specify exiting the process with failure code 1 after catching and printing an exception (thrown within func).

Returns

(*): Returns the return value of func.

Example

dantil.tryCatchWrapper(function () {
  // ...stuff...
  throw new Error('test failed')
})
// => Catches thrown exception and prints stack trace

dantil.deleteModuleCache([paths])

#

Removes the modules identified by the provided paths from cache, forcing them to be reloaded at next require() call.

Without removing a module from cache, subsequent require() calls to the same module will not enable changes to its file(s). This is useful for enabling changes on a server without restarting the server.

Arguments

  1. [paths] (...string): The paths of modules to remove from cache.

Example

var myModule = require('./myModule.js')
// => Loads module

dantil.deleteModuleCache('./myModule.js')
// => Removes module from cache

myModule = require('./myModule.js')
// => Loads module again, enabling changes to './myModule.js'

dantil.getLocation()

#

Gets this method's invocation location in the format filePath:lineNumber:columnNumber.

Returns

(string): Returns this method's invocation location.

Example

The contents of foo.js:

dantil.getLocation()
// => '/Users/Danny/foo.js:1'

dantil.getModuleCallerLocation()

#

Gets the location of the function call that invoked the currently executing module in the format filePath:lineNumber:columnNumber.

This is not necessarily the caller of the currently executing function, which can be another function within the same module. Nor is it necessarily this module's parent which instantiated the module. Rather, it is the most recent function call in the stack outside the currently executing module. • Skips stack frames for native Node functions (e.g., require()).

When searching the call stack, skips those frames for modules in which dantil.skipFileInLocationRetrieval() was invoked. • This is useful for including a method's invocation location in an error message, though that location is deep within the call stack relative to the error's generation location. I.e., the error is caught several modules deep from the invocation to which the error applies, as opposed to being one module deep.

Returns undefined if there is no other module in the stack below where this method was invoked that meets these criteria. This occurs when invoked from the root module.

Returns

(string): Returns the location of the function call that invoked the currently executing module.

Example

The contents of main.js:

var child = require('./child.js')
child.func()

var grandchild = require('./grandchild.js')
grandchild.foo()

// Try to get the frame of the nonexistent function call that invoked this module.
dantil.getModuleCallerLocation()
// => undefined

The contents of child.js:

var grandchild = require('./grandchild.js')

exports.func = function () {
  // Get the frame of the invocation of the current execution of this module.
  dantil.getModuleCallerLocation()
  // => '/Users/Danny/main.js:2'

  // Call another function within the same module, though retrieves the same frame.
  subFunc()

  // Call a function in another module.
  grandchild.bar()
}

function subFunc() {
  // Get the frame of the invocation of the current execution of this module (which
  // is not the frame that invoked this function).
  dantil.getModuleCallerLocation()
  // => '/Users/Danny/main.js:2'
}

The contents of grandchild.js:

exports.foo = function () {
  dantil.getModuleCallerLocation()
  // => '/Users/Danny/main.js:5'
}

exports.bar = function () {
  dantil.getModuleCallerLocation()
  // => '/Users/Danny/child.js:13'
}

dantil.skipFileInLocationRetrieval

#

Marks the module in which this method is invoked for dantil.getModuleCallerLocation() to skip when searching the call stack.

This is useful for using dantil.getModuleCallerLocation() to include a method's invocation location in an error message, though that location is deep within the call stack relative to the error's generation location. I.e., the error is caught several modules deep from the invocation to which the error applies, as opposed to being one module deep.

Example

The contents of main.js:

var child = require('./child.js')

// Invoke `child.js`.
child.func()

The contents of child.js:

var grandchild = require('./grandchild.js')

exports.func = function () {
  // Get the location of the function call that invoked the module `grandchild.js`.
  grandchild.getCallerLocation()
  // => '/Users/Danny/child.js:5:15'

  // Skip this module (`child.js`) when using `dantil.getModuleCallerLocation()`
  // in `grandchild.js` to get the location of the call that invoked the module's method.
  dantil.skipFileInLocationRetrieval()

  // Get the location of the function call that invoked this module, which
  // invoked the `grandchild.js` method.
  grandchild.getCallerLocation()
  // => '/Users/Danny/main.js:3:7'
}

The contents of grandchild.js:

exports.getCallerLocation = function () {
  // Get the location of the function call that invoked this module.
  return dantil.getModuleCallerLocation()
}

dantil.colors

#

(Object): Stylizes strings for printing to the console using the chalk module.

Example

console.log(dantil.colors.red('Error'))
// => Prints red-colored "Error"

“File System” Methods

dantil.stdoutToFile(path, func)

#

Invokes func while synchronously writing the process's stdout to a file at path instead of the console. Creates the file if it does not exist or truncates the file to zero length if it does exist. Restores stdout to the console when func returns or if an exception is thrown.

Arguments

  1. path (string): The path where to write stdout.
  2. func (Function): The function to invoke while writing output to path.

Returns

(*): Returns the value returned by func, if any.

Example

// Print to console.
console.log('Begin output to file')

// Redirect `stdout` from console to '~/Desktop/out.txt'.
dantil.stdoutToFile('~/Desktop/out.txt', function () {
  console.log('Numbers:')
  for (var i = 0; i < 100; ++i) {
    console.log(i)
  }
})
// => Restores `stdout` to console and prints "Output saved: ~/Desktop/out.txt"

// Print to console (after restoring `stdout`).
console.log('Output to file complete')

dantil.writeJSONFile(path, object)

#

Stringifies and writes object to a JSON file at path.

Arguments

  1. path (string): The file path to which to write.
  2. object (Object): The object to save to path.

Example

var obj = {
  name: 'foo',
  value: 7,
  list: [ 'apple', 'orange' ]
}

dantil.writeJSONFile('./myObj.json', obj)
// => Writes file and prints "File saved: /Users/Danny/myObj.json"

dantil.pathAndLineNumbersOf(filePath, value)

#

Gets the file path and line number in the format filePath:lineNumber of each occurrence of value in the source file at filePath. This is useful for error reporting.

Arguments

  1. filePath (string): The path of the source file to search.
  2. value (*): The value for which to search.

Returns

(Array): Returns the set of matched file paths and line numbers.

Example

The contents of foo.js:

var list = [
  { name: 'lorem', num: 2 },
  { name: 'lorem ipsum', num: 5 },
  { name: 'ipsum', num: 3 }
]

The contents of bar.js:

dantil.pathAndLineNumbersOf('./foo.js', 'ipsum')
// => [ '/Users/Danny/foo.js:3', '/Users/Danny/foo.js:3' ]

// Enclose sought value to distinguish `ipsum` from `'ipsum'`.
dantil.pathAndLineNumbersOf('./foo.js', '\'ipsum\'')
// => [ '/Users/Danny/foo.js:4' ]

dantil.firstPathAndLineNumberOf(filePath, value, [subValue])

#

Gets the file path and line number in the format filePath:lineNumber of the first occurrence of value in the source file at filePath. This is useful for error reporting.

If subValue is provided, gets the line number of the first occurrence of subValue after the first occurrence of value. This is useful for using value to distinguish multiple occurrences of subValue in the file.

Arguments

  1. filePath (string): The path of the source file to search.
  2. value (*): The value for which to search.
  3. [subValue] (*): The second value for which to search, starting at the location of value.

Returns

(string|undefined): Returns the matched file path and line number, else undefined.

Example

The contents of foo.js:

var list = [
  {
    name: 'lorem',
    num: 2
  }, {
    name: 'lorem ipsum',
    num: 5
  }, {
    name: 'ipsum',
    num: 3
  }
]

The contents of bar.js:

dantil.firstPathAndLineNumberOf('./foo.js', 'ipsum')
// => '/Users/Danny/foo.js:6',

// Get line number of first occurrence of `num` after `ipsum`.
dantil.firstPathAndLineNumberOf('./foo.js', 'ipsum', 'num')
// => '/Users/Danny/foo.js:7',

// Enclose sought value to distinguish `ipsum` from `'ipsum'`.
dantil.firstPathAndLineNumberOf('./foo.js', '\'ipsum\'')
// => '/Users/Danny/foo.js:9'

dantil.expandHomeDir(path)

#

Replaces '~' in path (if present and at the path's start) with the home directory path.

Arguments

  1. path (string): The file path.

Returns

(string): Returns path with '~', if present, replaced with the home directory path.

Example

dantil.expandHomeDir('~/Desktop')
// => '/Users/Danny/Desktop'

dantil.realpathSync(path)

#

Synchronously resolves path to an absolute path.

This method is similar to Node's fs.realpathSync(), but also expands '~' if found in path.

Arguments

  1. path (string): The path to resolve.

Returns

(string): Returns the absolute path.

Example

dantil.realpathSync('~/Desktop/../../Danny')
// => '/Users/Danny'

dantil.pathExistsSync(path)

#

Synchronously checks if path exists by checking the file system.

Replaces the deprecated fs.existsSync() by invoking fs.accessSync(path), which throws an exception when path is not found, within a try...catch block.

Arguments

  1. path (string): The path to check.

Returns

(boolean): Returns true if path exists, else false.

Example

dantil.pathExistsSync('/etc/passwd')
// => true

dantil.pathExistsSync('/wrong/path')
// => false

“Console” Methods

dantil.log([values])

#

Pretty-prints the provided values and objects to stdout, in color, recursing 2 times while formatting objects (which is the behavior of console.log()).

Formats plain Objects and Arrays with multi-line string representations on separate lines. Concatenates and formats all other consecutive values on the same line.

If the first argument is of a complex type (e.g., Object, Array), left-aligns all remaining lines. Otherwise, equally indents each line after the first line, if any. If the first argument has leading whitespace (or is entirely whitespace), prepends all remaining arguments with the same whitespace (as indentation) excluding newline characters.

Arguments

  1. [values] (...*): The values and objects to print.

Returns

(*): Returns the first argument.

Example

dantil.log({
  name: 'Danny',
  value: 3,
  terms: [ 'confident', 'farseeing', 'capable', 'prudent' ],
  exitFunc: process.exit,
  deepObject: {
    nestedArray: [ [ 1 ] ],
    nestedObject: { obj: { str: 'string', num: 2, bool: true, arr: [ 1, 2, 3, 4, 5, 6, 7 ] } }
  }
})

Output:
dantil.log() example output


dantil.dir([values])

#

A version of dantil.log() that recurses indefinitely while formatting objects. This is useful for inspecting large, complicated objects.

Arguments

  1. [values] (...*): The values and objects to print.

Returns

(*): Returns the first argument.

Example

dantil.dir({
  name: 'Danny',
  value: 3,
  terms: [ 'confident', 'farseeing', 'capable', 'prudent' ],
  exitFunc: process.exit,
  deepObject: {
    nestedArray: [ [ 1 ] ],
    nestedObject: { obj: { str: 'string', num: 2, bool: true, arr: [ 1, 2, 3, 4, 5, 6, 7 ] } }
  }
})

Output:
dantil.dir() example output


dantil.logObjectAtDepth(object, depth)

#

Prints object like dantil.log() but recurses depth times while formatting. This is useful for inspecting large, complicated objects.

Arguments

  1. object (Object): The object to print.
  2. depth (number): The number of times to recurse while formatting object.

Returns

(Object): Returns object.

Example

var obj = {
  name: 'Danny',
  nestedObj: { array: [ { isGood: false } ] }
}

dantil.logObjectAtDepth(obj, 1)
dantil.logObjectAtDepth(obj, 2)
dantil.logObjectAtDepth(obj, 3)

Output:
dantil.logObjectAtDepth() example output


dantil.logWithLine([values])

#

Prints the provided values like dantil.log(), preceded by this method's invocation location.

Arguments

  1. [values] (...*): The values and objects to print.

Returns

(*): Returns the first argument.

Example

dantil.logWithLine({
  name: 'Danny',
  value: 3,
  terms: [ 'confident', 'farseeing', 'capable', 'prudent' ],
  exitFunc: process.exit,
  deepObject: {
    nestedArray: [ [ 1 ] ],
    nestedObject: { obj: { str: 'string', num: 2, bool: true, arr: [ 1, 2, 3, 4, 5, 6, 7 ] } }
  }
})

Output:
dantil.logWithLine() example output


dantil.dirWithLine([values])

#

Prints the provided values like dantil.dir(), preceded by this method's invocation location.

Arguments

  1. [values] (...*): The values and objects to print.

Returns

(*): Returns the first argument.

Example

dantil.dirWithLine({
  name: 'Danny',
  value: 3,
  terms: [ 'confident', 'farseeing', 'capable', 'prudent' ],
  exitFunc: process.exit,
  deepObject: {
    nestedArray: [ [ 1 ] ],
    nestedObject: { obj: { str: 'string', num: 2, bool: true, arr: [ 1, 2, 3, 4, 5, 6, 7 ] } }
  }
})

Output:
dantil.dirWithLine() example output


dantil.logStderr([values])

#

A version of dantil.log() that prints to stderr.

Arguments

  1. [values] (...*): The values and objects to print.

Returns

(*): Returns the first argument.


dantil.stylize(value, [options])

#

Formats value in color for pretty-printing, recursing options.depth times while formatting.

This method is similar to Node's util.inspect(), but formats in color by default if the terminal supports color.

Arguments

  1. value (*): The object or value to stylize.
  2. [options] (Object): The options object.
  3. [options.colors=true] (boolean): Specify coloring the string for pretty-printing.
  4. [options.depth=2] (number): The number of times to recurse while formating value if of a complex type. Pass null to recurse indefinitely.

Returns

(string): Returns a stylized string representation of value.


dantil.logError([values])

#

Prints the provided values like dantil.log() prepended with red-colored "Error: ".

If the first character of the first value is a newline character, moves the character to before "Error: ".

Arguments

  1. [values] (...*): The values to print following "Error: ".

Returns

(*): Returns the first argument.

Example

dantil.logError('Failed', numTestsFailed, 'of', tests.length, 'tests')

Output:
dantil.logError() example output


dantil.logErrorWithNewLine([values])

#

Prints the provided values like dantil.logError(), followed by a trailing newline.

Arguments

  1. [values] (...*): The values to print following "Error: ".

Returns

(*): Returns the first argument.

Example

dantil.logErrorWithNewLine('Failed', numTestsFailed, 'of', tests.length, 'tests')

Output:
dantil.logErrorWithNewLine() example output


dantil.logWarning([values])

#

Prints the provided values like dantil.log() prepended with yellow-colored "Warning: ".

If the first character of the first value is a newline character, moves the character to before "Warning: ".

Arguments

  1. [values] (...*): The values to print following "Warning: ".

Returns

(*): Returns the first argument.

Example

dantil.logWarning('Missing property:', obj)

Output:
dantil.logWarning() example output


dantil.logSuccess([values])

#

Prints the provided values like dantil.log() prepended with green-colored "Success: ".

If the first character of the first value is a newline character, moves the character to before "Success: ".

Arguments

  1. [values] (...*): The values to print following "Success: ".

Returns

(*): Returns the first argument.

Example

dantil.logSuccess(tests.length, 'tests passed')

Output:
dantil.logSuccess() example output


dantil.logErrorAndPath([logThisLine], [values])

#

Prints the provided values in an error message like dantil.logError() followed by the file path and line number of the function call that invoked the currently executing module.

Arguments

  1. [logThisLine] (boolean): Specify logging the line where this method is called instead of the line which invoked the currently executing module.
  2. [values] (...*): The values to print following "Error: ".

Returns

(*): Returns the first argument.

Example

The contents of foo.js:

dantil.logErrorAndPath('Failed', numTestsFailed, 'of', tests.length, 'tests')

Output:
dantil.logErrorAndPath() example output


dantil.logWarningAndPath([logThisLine], [values])

#

Prints the provided values in a warning message like dantil.logWarning() followed by the file path and line number of the function call that invoked the currently executing module.

Arguments

  1. [logThisLine] (boolean): Specify logging the line where this method is called instead of the line which invoked the currently executing module.
  2. [values] (...*): The values to print following "Warning: ".

Returns

(*): Returns the first argument.

Example

The contents of foo.js:

var badObj = { name: 'danny', age: undefined }
dantil.logWarningAndPath('Property undefined:', badObj)

Output:
dantil.logWarningAndPath() example output


dantil.logPathAndObject(object, [logThisLine])

#

Prints object preceded by the file path and line number of the function call that invoked the currently executing module. Surrounds output with a leading newline and a trailing newline.

Arguments

  1. object (Object): The object to print.
  2. [logThisLine] (boolean): Specify logging the line where this method is called instead of the line which invoked the currently executing module.

Returns

(Object): Returns object.

Example

The contents of foo.js:

var obj = {
  values: [1, 2, 3],
  name: 'danny'
}

dantil.logPathAndObject(obj)

Output:
dantil.logPathAndObject() example output


dantil.logTrace([message])

#

Prints the stack trace to the current position with danti.prettifyStackTrace() stylization.

Arguments

  1. [message] (string): The optional message to print above the stack trace.

Example

dantil.logTrace('Reached obscure condition')

Output:
dantil.logTrace() example output


dantil.logLine([label])

#

Prints the file path and line number, prepended with label if provided else the invoking function's name. This is useful to mark reaching a section of code.

Arguments

  1. [label] (string): The label to prepend to the path and line number instead of the calling function name.

Example

The contents of foo.js:

function myFunction() {
  dantil.logLine()
}

Output:
dantil.logLine() example output

function myFunction() {
  dantil.logLine('Bad area reached!')
}

Output:
dantil.logLine(label) example output


dantil.logLineIf(value, [label])

#

If value is truthy, prints the file path and line number, prepended with label if provided else the invoking function's name. This is useful to mark reaching a section of code.

Arguments

  1. value (*): The value to check if truthy.
  2. [label] (string): The label to prepend to the path and line number instead of the calling function

Example

The contents of foo.js:

function myFunction(myCondition) {
  dantil.logLineIf(myCondition)
}

Output:
dantil.logLineIf() example output

function myFunction(myCondition) {
  dantil.logLineIf(myCondition, 'Condition met!')
}

Output:
dantil.logLineIf(label) example output


dantil.prettifyStackTrace([removePathParens])

#

Modifies V8's default stack trace format (when printing) to stylize output.

Arguments

  1. [removePathParens] (boolean): Specify removing parentheses that surround file paths. This prevents parentheses from breaking iTerm's open-file-path shortcut in iTerm v2.x.

Example

dantil.prettifyStackTrace()
// => Prettifies all subsequent stack traces

Before:
Before invoking dantil.prettifyStackTrace() After:
After invoking dantil.prettifyStackTrace()


“Profiling” Methods

dantil.assertEqual(value, other, [message])

#

Tests shallow, coercive equality with the equal comparison operator (==). If the test fails, prints an error message and the file path and line number to stderr. In contrast, Node's assert.equal() throws an exception.

Arguments

  1. value (*): The value to compare.
  2. other (*): The other value to compare.
  3. [message] (string): The optional message to print if the test fails.

Returns

(boolean): Returns true if the values are equivalent, else false.

Example

The contents of foo.js:

dantil.assertEqual(false, 0)
// => true

dantil.assertEqual(20, 21)
// => false
// => Prints: AssertionError: 20 == 21
//              /Users/Danny/foo.js:4

dantil.assertEqual({ prop: 'value' }, { prop: 'value' })
// => false
// => Prints: AssertionError: { prop: 'value' } == { prop: 'value' }
//              /Users/Danny/foo.js:9

dantil.assertEqual([ 3, 1, 4 ], [ 1, 5, 9 ], 'Array test failed')
// => false
// => Prints: AssertionError: Array test failed: [ 3, 1, 4 ] == [ 1, 5, 9 ]
//              /Users/Danny/foo.js:14

if (dantil.assertEqual(myArray.length, 100)) {
  // => true

  // ...stuff...
}

dantil.time(label)

#

Starts a high-resolution timer (with precision in microseconds) identified by label. Use dantil.timeEnd(label) to print the timer's current value.

Arguments

  1. label (string): The timer identifier.

Example

// Start timer
dantil.time('my test')

// ...stuff...

dantil.timeEnd('my test')
// => Prints "my test: 13.264 ms"

// ...more stuff...

dantil.timeEnd('my test')
// => Prints "my test: 31.183 ms"

dantil.timeEnd(label)

#

Prints the current high-resolution value of a timer initiated with dantil.time(label).

Arguments

  1. label (string): The timer identifier.

dantil.count(label)

#

Increments the invocation count for label. Use dantil.end(label) or dantil.endAll() to print the counter's value. This is useful to profile the number of times a section of code is reached.

Arguments

  1. label (string): The counter identifier.

Example

for (var i = 0; i < 100; ++i) {
  if (i % 2 === 0) dantil.count('even')
}

dantil.countEnd('even')
// => Resets the count for 'even' to 0
// => Prints "even: 50"

dantil.countEnd(label)

#

Prints (and resets the value of) the number of dantil.count(label) invocations.

Arguments

  1. label (string): The counter identifier.

dantil.countEndAll

#

Prints (and resets the values of) the counter value of each label recorded by counter.count(), and each counter's value as a percentage of all counters.

Does not print counters that are never reached (having not initialized their keys). Prints counts in order of decreasing value.

Example

for (var i = 0; i < 99; ++i) {
  dantil.count(i % 2 === 0 ? 'even' : 'odd')
}

dantil.countEndAll()
// => Prints counts for all labels and resets all to 0

Output:
dantil.countEndAll() example output


“Lang” Methods

dantil.clone(value)

#

Creates a shallow clone of value.

Arguments

  1. value (*): The value to clone.

Returns

(*): Returns the cloned value.

Example

var objects = [ { a: 1 }, { b: 2 } ]

var shallow = dantil.clone(objects)
shallow === objects
// => false
shallow[0] === objects[0]
// => true

dantil.isDeepEqual(value, other, [customizer], [thisArg])

#

Performs a deep comparison between two values to determine if they are equivalent using the lodash.isEqual module.

Arguments

  1. value (*): The value to compare.
  2. other (*): The other value to compare.
  3. [customizer] (Function): The function to customize value comparisons.
  4. [thisArg] (*): The this binding of customizer.

Returns

(boolean): Returns true if the values are equivalent, else false.

Example

var object = { user: 'fred' }
var other = { user: 'fred' }

object == other
// => false

dantil.isDeepEqual(object, other)
// => true

“Function” Methods

dantil.unary(func)

#

Creates a function that accepts up to one argument, ignoring any additional arguments.

Arguments

  1. func (Function): The function for which to cap arguments.

Returns

(Function): Returns the new function.

Example

[ '3', '1', '4' ].map(dantil.unary(parseInt))
// => [ 3, 1, 4 ]

“Object” Methods

dantil.objectsEqual(a, b)

#

Performs a shallow comparison between two objects to determine if they are equivalent.

Arguments

  1. a (Object): The object to compare.
  2. b (Object): The other object to compare.

Returns

(boolean): Returns true if the objects are equivalent, else false.

Example

dantil.objectsEqual({}, {})
// => true

dantil.objectsEqual({ name: 'danny', val: 1 }, { name: 'danny', val: 1 })
// => true

dantil.objectsEqual({ name: 'danny' }, { val: 1 })
// => false

// A shallow comparison will compare complex type references, not their contents.
var objA = { prop: 'val' }
var objB = { prop: 'val' }
dantil.objectsEqual({ name: 'danny', obj: objA }, { name: 'danny', obj: objB })
// => false

// Rather, objects are only equal if they are the same instance.
dantil.objectsEqual({ a: objA, b: objB }, { a: objA, b: objB })
// => true

dantil.deleteUndefinedObjectProps(object)

#

Clones and recursively removes all properties of object defined as undefined. This is useful for object comparisons and pretty-printing.

Arguments

  1. object (Object): The Object to purge of properties defined as undefined.

Returns

(Object): Returns the clone of object without undefined properties.


dantil.diffObjects(object, other, [collapsed])

#

Compares two objects line by line and stylizes the differences for printing.

Arguments

  1. object (Object): The object to compare.
  2. other (Object): The other object to compare.
  3. [collapsed] (boolean): Specify putting ranges of unchanged lines in a fold.

Returns

(string): Returns a string of the differences stylized for printing.

Example

var objA = {
  name: 'dantil',
  author: 'Danny',
  version: 0.1,
  sagan: [
    'It has been said that astronomy is a humbling and character-building',
    'experience. There is perhaps no better demonstration of the folly of',
    'human conceits than this distant image of our tiny world. To me, it',
    'underscores our responsibility to deal more kindly with one another,',
    'and to preserve and cherish the pale blue dot, the only home we\'ve'
  ]
}

var objB = {
  name: 'dantil',
  author: 'Danny',
  version: 0.2,
  sagan: [
    'It has been said that astronomy is a humbling and character-building',
    'experience. There is perhaps no better demonstration of the folly of',
    'human conceits than this distant image of our tiny world. To me, it',
    'underscores our responsibility to deal more kindly with one another,',
    'ever known.'
  ]
}
// Compare objects and generate string with differences stylized.
console.log(dantil.diffObjects(objA, objB))

Output:
dantil.diffObjects() example output

// Collapse ranges of unchanged lines.
console.log(dantil.diffObjects(objA, objB, true))

Collapsed output:
dantil.diffObjects() collapsed example output


“Array” Methods

dantil.arraysEqual(a, b, [predicate])

#

Performs a shallow comparison between two arrays to determine if they are equivalent.

If predicate is provided, checks if returns truthy when invoked per index with the values of both arrays at that index as arguments: (elementA, elementB).

Arguments

  1. a (Array): The array to compare.
  2. b (Array): The other array to compare.
  3. [predicate] (Function): The function invoked per index.

Returns

(boolean): Returns true if the arrays are equivalent, else false.

Example

dantil.arraysEqual([], [])
// => true

dantil.arraysEqual([1, 2, 3, 'danny'], [1, 2, 3, 'danny'])
// => true

dantil.arraysEqual([ false, true ], [ true ])
// => false

// A shallow comparison will compare complex type references, not their contents.
var objA = { prop: 'val' }
var objB = { prop: 'val' }
var objC = { prop: undefined }
dantil.arraysEqual([ objA, objC ], [ objB, objC ])
// => false

// Compare elements at each index using `dantil.objectsEqual`.
dantil.arraysEqual([ objA, objC ], [ objB, objC ], dantil.objectsEqual)
// => true

// Rather, objects are only equal if they are the same instance.
dantil.arraysEqual([ objA, objB ], [ objA, objB ])
// => true

dantil.new2DArray(length, [subLength=0])

#

Creates a new two-dimensional array with length length.

Arguments

  1. length (number): The length of the new array (i.e., the first dimension).
  2. [subLength=0] (number): The length of each sub-array (i.e., the second dimension).

Returns

(Array): Returns the new two-dimensional array.

Example

dantil.new2DArray(5)
// => [ [], [], [], [], [] ]

dantil.new2DArray(4, 2)
// => [ [ ,  ], [ ,  ], [ ,  ], [ ,  ] ]

dantil.without(array, [values])

#

Creates a new array from array excluding all provided values.

Arguments

  1. array (Array): The array to filter.
  2. [values] (...*): The values to exclude.

Returns

(Array): Returns the new array of filtered values.

Example

dantil.without([ 3, 1, 4, 1, 5 ], 1, 5)
// => [ 3, 4 ]

“Number” Methods

dantil.cleanFloat(number)

#

Removes any extraneous digits from number, which result from operations limited by JavaScript's floating point number precision, such as 0.1 * 0.2 (which does not equal 0.02). This limitation results from being unable to map 0.1 to a finite binary floating point number.

Arguments

  1. number (number): The number to rid of any extraneous digits.

Returns

(number): Returns the cleaned number.

Example

var number = 0.1 * 0.2
// => 0.020000000000000004

number = dantil.cleanFloat(number)
// => 0.02

“String” Methods

dantil.diffStrings(expected, actual)

#

Compares two strings word by word and stylizes the differences for printing.

Arguments

  1. expected (string): The string to compare.
  2. actual (string): The other string to compare.

Returns

(Object): Returns an object with expected and actual as properties for the strings with their differences stylized for printing.

Example

var expected = 'We long to be here for a purpose, even though, despite much self-deception, none is evident.'
var actual = 'We all long for a purpose, even though none is evident.'

// Compare strings and style the differences.
var diff = dantil.diffStrings(expected, actual)
console.log(diff.expected)
console.log(diff.actual)

Output:
dantil.diffStrings() example output


dantil.format(string, [placeholderVals])

#

Formats a string in a printf()-like format using Node's util.format().

Arguments

  1. string (string): The string to format containing zero or more placeholders. Each placeholder is replaced with the converted value from its corresponding argument.
  2. [placeholderVals] (...string): The values to replace the corresponding placeholders in string.

Returns

(string): Returns the formatted string.

Example

dantil.format('%s:%s %d', 'foo', 'bar', 22)
// => 'foo:bar 22'

dantil.kebabToCamelCase(kebabCasedString)

#

Converts kebab cased string to camel case.

Arguments

  1. kebabCasedString (string): The kebab cased string to convert.

Returns

(string): Returns the camel cased string.

Example

dantil.kebabToCamelCase('my-long-variable-name')
// => 'myLongVariableName'

dantil.camelToKebabCase(camelCasedString)

#

Converts camel cased string to kebab case.

Arguments

  1. camelCasedString (string): The camel cased string to convert.

Returns

(string): Returns the kebab cased string.

Example

dantil.camelToKebabCase('myLongVariableName')
// => 'my-long-variable-name'

dantil.enquote(string)

#

Encloses string in single quotes.

Arguments

  1. string (string): The string to enclose with single quotes.

Returns

(string): Returns the enquoted string.

Example

dantil.enquote('my string')
// => '\'my string\''

About

A Node.js utility library.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published