A Node.js utility library.
In addition to much original functionality, includes many improved alternatives to native functions.
npm install dannynemer/dantil
var dantil = require('dantil')
dantil.illFormedOpts
dantil.tryCatchWrapper
dantil.deleteModuleCache
dantil.getLocation
dantil.getModuleCallerLocation
dantil.skipFileInLocationRetrieval
dantil.colors
dantil.stdoutToFile
dantil.writeJSONFile
dantil.pathAndLineNumbersOf
dantil.firstPathAndLineNumberOf
dantil.expandHomeDir
dantil.realpathSync
dantil.pathExistsSync
dantil.log
dantil.dir
dantil.logObjectAtDepth
dantil.logWithLine
dantil.dirWithLine
dantil.logStderr
dantil.stylize
dantil.logError
dantil.logErrorWithNewLine
dantil.logWarning
dantil.logSuccess
dantil.logErrorAndPath
dantil.logWarningAndPath
dantil.logPathAndObject
dantil.logTrace
dantil.logLine
dantil.logLineIf
dantil.prettifyStackTrace
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).
schema
(Object): The definition of required and optional properties foroptions
.[options]
(Object): The options object to check for conformity toschema
.[ignoreUndefined]
(Object): Specify ignoring non-required
options
properties defined asundefined
. Otherwise, reports them as errors, which is useful for catching broken references.
(boolean): Returns true
if options
is ill-formed, else false
.
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' })
Invokes func
within a try
block, and catches and prints any thrown exceptions (including the stack trace if an Error
is thrown).
func
(Function): The function to invoke within atry
block.[exitProcessIfFailure]
(boolean): Specify exiting the process with failure code1
after catching and printing an exception (thrown withinfunc
).
(*): Returns the return value of func
.
dantil.tryCatchWrapper(function () {
// ...stuff...
throw new Error('test failed')
})
// => Catches thrown exception and prints stack trace
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.
[paths]
(...string): The paths of modules to remove from cache.
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'
Gets this method's invocation location in the format filePath:lineNumber:columnNumber
.
(string): Returns this method's invocation location.
The contents of foo.js
:
dantil.getLocation()
// => '/Users/Danny/foo.js:1'
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.
(string): Returns the location of the function call that invoked the currently executing module.
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'
}
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.
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()
}
(Object): Stylizes strings for printing to the console using the chalk
module.
console.log(dantil.colors.red('Error'))
// => Prints red-colored "Error"
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.
path
(string): The path where to writestdout
.func
(Function): The function to invoke while writing output topath
.
(*): Returns the value returned by func
, if any.
// 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')
Stringifies and writes object
to a JSON file at path
.
path
(string): The file path to which to write.object
(Object): The object to save topath
.
var obj = {
name: 'foo',
value: 7,
list: [ 'apple', 'orange' ]
}
dantil.writeJSONFile('./myObj.json', obj)
// => Writes file and prints "File saved: /Users/Danny/myObj.json"
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.
filePath
(string): The path of the source file to search.value
(*): The value for which to search.
(Array): Returns the set of matched file paths and line numbers.
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' ]
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.
filePath
(string): The path of the source file to search.value
(*): The value for which to search.[subValue]
(*): The second value for which to search, starting at the location ofvalue
.
(string|undefined): Returns the matched file path and line number, else undefined
.
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'
Replaces '~'
in path
(if present and at the path's start) with the home directory path.
path
(string): The file path.
(string): Returns path
with '~'
, if present, replaced with the home directory path.
dantil.expandHomeDir('~/Desktop')
// => '/Users/Danny/Desktop'
Synchronously resolves path
to an absolute path.
This method is similar to Node's fs.realpathSync()
, but also expands '~'
if found in path
.
path
(string): The path to resolve.
(string): Returns the absolute path.
dantil.realpathSync('~/Desktop/../../Danny')
// => '/Users/Danny'
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.
path
(string): The path to check.
(boolean): Returns true
if path
exists, else false
.
dantil.pathExistsSync('/etc/passwd')
// => true
dantil.pathExistsSync('/wrong/path')
// => false
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 Object
s and Array
s 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.
[values]
(...*): The values and objects to print.
(*): Returns the first argument.
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 ] } }
}
})
A version of dantil.log()
that recurses indefinitely while formatting objects. This is useful for inspecting large, complicated objects.
[values]
(...*): The values and objects to print.
(*): Returns the first argument.
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 ] } }
}
})
Prints object
like dantil.log()
but recurses depth
times while formatting. This is useful for inspecting large, complicated objects.
object
(Object): The object to print.depth
(number): The number of times to recurse while formattingobject
.
(Object): Returns object
.
var obj = {
name: 'Danny',
nestedObj: { array: [ { isGood: false } ] }
}
dantil.logObjectAtDepth(obj, 1)
dantil.logObjectAtDepth(obj, 2)
dantil.logObjectAtDepth(obj, 3)
Prints the provided values like dantil.log()
, preceded by this method's invocation location.
[values]
(...*): The values and objects to print.
(*): Returns the first argument.
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 ] } }
}
})
Prints the provided values like dantil.dir()
, preceded by this method's invocation location.
[values]
(...*): The values and objects to print.
(*): Returns the first argument.
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 ] } }
}
})
A version of dantil.log()
that prints to stderr
.
[values]
(...*): The values and objects to print.
(*): Returns the first argument.
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.
value
(*): The object or value to stylize.[options]
(Object): The options object.[options.colors=true]
(boolean): Specify coloring the string for pretty-printing.[options.depth=2]
(number): The number of times to recurse while formatingvalue
if of a complex type. Passnull
to recurse indefinitely.
(string): Returns a stylized string representation of value
.
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: ".
[values]
(...*): The values to print following "Error: ".
(*): Returns the first argument.
dantil.logError('Failed', numTestsFailed, 'of', tests.length, 'tests')
Prints the provided values like dantil.logError()
, followed by a trailing newline.
[values]
(...*): The values to print following "Error: ".
(*): Returns the first argument.
dantil.logErrorWithNewLine('Failed', numTestsFailed, 'of', tests.length, 'tests')
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: ".
[values]
(...*): The values to print following "Warning: ".
(*): Returns the first argument.
dantil.logWarning('Missing property:', obj)
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: ".
[values]
(...*): The values to print following "Success: ".
(*): Returns the first argument.
dantil.logSuccess(tests.length, 'tests passed')
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.
[logThisLine]
(boolean): Specify logging the line where this method is called instead of the line which invoked the currently executing module.[values]
(...*): The values to print following "Error: ".
(*): Returns the first argument.
The contents of foo.js
:
dantil.logErrorAndPath('Failed', numTestsFailed, 'of', tests.length, 'tests')
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.
[logThisLine]
(boolean): Specify logging the line where this method is called instead of the line which invoked the currently executing module.[values]
(...*): The values to print following "Warning: ".
(*): Returns the first argument.
The contents of foo.js
:
var badObj = { name: 'danny', age: undefined }
dantil.logWarningAndPath('Property undefined:', badObj)
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.
object
(Object): The object to print.[logThisLine]
(boolean): Specify logging the line where this method is called instead of the line which invoked the currently executing module.
(Object): Returns object
.
The contents of foo.js
:
var obj = {
values: [1, 2, 3],
name: 'danny'
}
dantil.logPathAndObject(obj)
Prints the stack trace to the current position with danti.prettifyStackTrace()
stylization.
[message]
(string): The optional message to print above the stack trace.
dantil.logTrace('Reached obscure condition')
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.
[label]
(string): The label to prepend to the path and line number instead of the calling function name.
The contents of foo.js
:
function myFunction() {
dantil.logLine()
}
function myFunction() {
dantil.logLine('Bad area reached!')
}
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.
value
(*): The value to check if truthy.[label]
(string): The label to prepend to the path and line number instead of the calling function
The contents of foo.js
:
function myFunction(myCondition) {
dantil.logLineIf(myCondition)
}
function myFunction(myCondition) {
dantil.logLineIf(myCondition, 'Condition met!')
}
Modifies V8's default stack trace format (when printing) to stylize output.
[removePathParens]
(boolean): Specify removing parentheses that surround file paths. This prevents parentheses from breaking iTerm's open-file-path shortcut in iTerm v2.x.
dantil.prettifyStackTrace()
// => Prettifies all subsequent stack traces
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.
value
(*): The value to compare.other
(*): The other value to compare.[message]
(string): The optional message to print if the test fails.
(boolean): Returns true
if the values are equivalent, else false
.
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...
}
Starts a high-resolution timer (with precision in microseconds) identified by label
. Use dantil.timeEnd(label)
to print the timer's current value.
label
(string): The timer identifier.
// 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"
Prints the current high-resolution value of a timer initiated with dantil.time(label)
.
label
(string): The timer identifier.
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.
label
(string): The counter identifier.
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"
Prints (and resets the value of) the number of dantil.count(label)
invocations.
label
(string): The counter identifier.
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.
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
Creates a shallow clone of value
.
value
(*): The value to clone.
(*): Returns the cloned value.
var objects = [ { a: 1 }, { b: 2 } ]
var shallow = dantil.clone(objects)
shallow === objects
// => false
shallow[0] === objects[0]
// => true
Performs a deep comparison between two values to determine if they are equivalent using the lodash.isEqual
module.
value
(*): The value to compare.other
(*): The other value to compare.[customizer]
(Function): The function to customize value comparisons.[thisArg]
(*): Thethis
binding ofcustomizer
.
(boolean): Returns true
if the values are equivalent, else false
.
var object = { user: 'fred' }
var other = { user: 'fred' }
object == other
// => false
dantil.isDeepEqual(object, other)
// => true
Creates a function that accepts up to one argument, ignoring any additional arguments.
func
(Function): The function for which to cap arguments.
(Function): Returns the new function.
[ '3', '1', '4' ].map(dantil.unary(parseInt))
// => [ 3, 1, 4 ]
Performs a shallow comparison between two objects to determine if they are equivalent.
a
(Object): The object to compare.b
(Object): The other object to compare.
(boolean): Returns true
if the objects are equivalent, else false
.
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
Clones and recursively removes all properties of object
defined as undefined
. This is useful for object comparisons and pretty-printing.
object
(Object): TheObject
to purge of properties defined asundefined
.
(Object): Returns the clone of object
without undefined
properties.
Compares two objects line by line and stylizes the differences for printing.
object
(Object): The object to compare.other
(Object): The other object to compare.[collapsed]
(boolean): Specify putting ranges of unchanged lines in a fold.
(string): Returns a string of the differences stylized for printing.
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))
// Collapse ranges of unchanged lines.
console.log(dantil.diffObjects(objA, objB, true))
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).
a
(Array): The array to compare.b
(Array): The other array to compare.[predicate]
(Function): The function invoked per index.
(boolean): Returns true
if the arrays are equivalent, else false
.
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
Creates a new two-dimensional array with length length
.
length
(number): The length of the new array (i.e., the first dimension).[subLength=0]
(number): The length of each sub-array (i.e., the second dimension).
(Array): Returns the new two-dimensional array.
dantil.new2DArray(5)
// => [ [], [], [], [], [] ]
dantil.new2DArray(4, 2)
// => [ [ , ], [ , ], [ , ], [ , ] ]
Creates a new array from array
excluding all provided values.
array
(Array): The array to filter.[values]
(...*): The values to exclude.
(Array): Returns the new array of filtered values.
dantil.without([ 3, 1, 4, 1, 5 ], 1, 5)
// => [ 3, 4 ]
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.
number
(number): The number to rid of any extraneous digits.
(number): Returns the cleaned number.
var number = 0.1 * 0.2
// => 0.020000000000000004
number = dantil.cleanFloat(number)
// => 0.02
Compares two strings word by word and stylizes the differences for printing.
expected
(string): The string to compare.actual
(string): The other string to compare.
(Object): Returns an object with expected
and actual
as properties for the strings with their differences stylized for printing.
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)
Formats a string in a printf()
-like format using Node's util.format()
.
string
(string): The string to format containing zero or more placeholders. Each placeholder is replaced with the converted value from its corresponding argument.[placeholderVals]
(...string): The values to replace the corresponding placeholders instring
.
(string): Returns the formatted string.
dantil.format('%s:%s %d', 'foo', 'bar', 22)
// => 'foo:bar 22'
Converts kebab cased string
to camel case.
kebabCasedString
(string): The kebab cased string to convert.
(string): Returns the camel cased string.
dantil.kebabToCamelCase('my-long-variable-name')
// => 'myLongVariableName'
Converts camel cased string
to kebab case.
camelCasedString
(string): The camel cased string to convert.
(string): Returns the kebab cased string.
dantil.camelToKebabCase('myLongVariableName')
// => 'my-long-variable-name'
Encloses string
in single quotes.
string
(string): The string to enclose with single quotes.
(string): Returns the enquoted string.
dantil.enquote('my string')
// => '\'my string\''