Class NoDash

class NoDash
NoDash.js is a terse utility library based on ES5 features

Defined in: nodash.js, line 129

Description (skip)

NoDash.js is a terse utility library based on ES5 features.

NoDash differs from already established utility libraries (such as Underscore.js un: and LoDash lo:):

NoDash was written from scratch for Sqimitive (sq@) as a replacement for Underscore. Usually you can just swap it in place of Underscore or LoDash but do check COMPATIBILITY for nuances.

npm npm install nodash

NoDash works with any module system: Node, AMD or “window”. In the latter, it assumes two global objects: NoDash and _ (see noConflict()).

Basic conventions

Constants

NODASH

Version of the library in use.

Example
if (_.NODASH) { ... }

Defined in: nodash.js, line 193Show code

NODASH: '0.9',

Methods

ajax ( options )

Performs a remote request using XMLHttpRequest and a subset of jQuery’s ajax() API.

Result Types
Types Notes
XMLHttpRequest The xhr
Arguments
Name Types Notes
optionsobject

Possible options keys:

Arguments
Name Types Notes
urlstr
typestr GET by default.
datastr Request data for POST, etc.
FormData, Blob, URLSearchParams (not in IE), etc.
dataTypestr Type of xhr.response, from standard mdn:XMLHttpRequestResponseType; text by default; other useful types are document (for HTML and XML) and json
contextobject Calling context for below callbacks.
beforeSendfunction Called before xhr.open(); receives xhr and options (mutable, affects internal copy, not given options); if returns === false then the request is not performed and error is called without giving e (imitates abort()).
successfunction Called when response has arrived; receives xhr and e
errorfunction Called on a request or response error, and also on beforeSend and xhr.abort(); receives xhr (always) and e (only if not on beforeSend).
completefunction Called after completion, successful or not; receives xhr and e
progressfunction Called during response transmission; receives xhr and e where useful e properties are:
Arguments
Name Types Notes
lengthComputablebool
loadedint bytes
totalint bytes Or 0.
timeoutint milliseconds If exceeded, request error’s with the status of 0.
headersobject Members can be strings or arrays; by default has X-Requested-With: XMLHttpRequest and, if type is not GET, Content-Type: application/x-www-form-urlencoded
usernamestr For HTTP Basic Authentication.
passwordstr For HTTP Basic Authentication.

It is guaranteed that, per given ajax() call:

  • exactly one of success or error and one complete is called
  • success is called on a 200-299 status and responseType matching dataType (the latter is browser-dependent and not very reliable)
  • complete is called after success or error, even if the latter has thrown an exception (it’s re-thrown after complete provided it didn’t throw another one)
  • progress is never called after calling success or error

ECMAScript equivalents: mdn:XMLHttpRequest, mdn:Fetch_API.

Example
_.ajax({
  url: 'form.php',
  type: 'POST',
  data: new FormData(document.querySelector('form')),
})

_.ajax({
  url:          'some.json',
  dataType:     'json',
  timeout:      5000,  // 5 seconds.
  headers:      {},    // remove X-Requested-With.
  beforeSend:   () => $('#loading').show()
  complete:     () => $('#loading').hide()
  success:      xhr => alert(xhr.response),
  error:        (xhr, e) => alert(xhr.statusText),
  progress:     (xhr, e) => $('progress').attr({
    max: e.total,
    value: e.lengthComputable && e.total
  }),
})

Defined in: nodash.js, lines 1998-2079 (82 lines) • Show code

ajax: function (options) {
  var o = NoDash.assign({}, {
    url: location.href,
    type: 'GET',
    data: undefined,
    dataType: 'text',
    context: undefined,
    beforeSend: new Function,
    success: new Function,
    error: new Function,
    complete: new Function,
    progress: new Function,
    timeout: 0,
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    username: undefined,
    password: undefined,
  }, options)

  if (o.type != 'GET' && !o.headers['Content-Type']) {
    o.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }

  var xhr = new XMLHttpRequest
  var queue = []

  var finish = function () {
    // Delayed processing to let all other events (errors) pass through.
    queue.length || NoDash.defer(function () {
      // No pop() - queue.length must be non-0 to prevent late XHR events
      // from re-triggering this.
      var args = [xhr].concat(ap.slice.call(queue[queue.length - 1]))
      var ok = xhr.status >= 200 && xhr.status < 300 &&
               // This check isn't very reliable as at least Firefox leaves
               // 'json' as is even if response is 'text/html'.
               xhr.responseType == o.dataType

      try {
        NoDash.bind(ok ? o.success : o.error).apply(o.context, args)
      } catch (e) {
        var ex = e
      }
      NoDash.bind(o.complete).apply(o.context, args)
      if (ex) { throw ex }
    })

    queue.push(arguments)
  }

  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
      finish.apply(undefined, arguments)
    }
  }

  // ontimeout is fired after onreadystatechange.
  xhr.ontimeout = finish

  xhr.upload.onprogress = function () {
    if (!queue.length) {
      var args = [xhr].concat(ap.slice.call(arguments))
      NoDash.bind(o.progress).apply(o.context, args)
    }
  }

  if (NoDash.bind(o.beforeSend).call(o.context, xhr, o) === false) {
    NoDash.bind(o.error).call(o.context, xhr)
  } else {
    xhr.open(o.type, o.url, true, o.username, o.password)
    xhr.timeout = o.timeout
    xhr.responseType = o.dataType

    NoDash.forEach(o.headers, function (value, name) {
      NoDash.toArray(value).forEach(function (item) {
        xhr.setRequestHeader(name, item)
      })
    })

    xhr.send(o.data)
  }

  return xhr
},
allKeys ( value )

Returns an array of all keys of value, including non-own.

Arguments
Name Types Notes
valueobject

See also hasOwn(), values(). Warning: uses for..in that is terribly slow for objects with prototype chains (not just {}).

from unordgen

Attention: JavaScript objects are unordered.

allKeys() returns keys in arbitrary order.

Example
function Class() { this.own = 1 }
Class.prototype.inherited = 2

_.hasOwn(new Class, 'inherited')    //=> false
_.allKeys(new Class)                //=> ['own', 'inherited']
_.values(new Class)                 //=> [1]

Defined in: nodash.js, lines 1665-1669 (5 lines) • Show code

allKeys: function (value) {
  var res = []
  for (var key in value) { res.push(key) }
  return res
},
assign ( ...objects )

Merges members of given objects into the first argument, overwriting keys of earlier arguments with later ones.

Result Types
Types Notes
object obj1
Arguments
Name Types Notes
objects Only object-type arguments.

ECMAScript equivalent: o:Object/assign. See also union(), intersection().

Warning: assign() mutates the first argument (and returns it).

Example
_.assign({})              //=> the argument unchanged
_.assign({}, {a: 1})      //=> first argument changed to {a: 1}
_.assign({b: 3}, {b: 4})  //=> first argument changed to {b: 4}

Only own properties are considered (hasOwn()):

_.assign({toString: f}, {})
  //=> first argument unchanged, even though: 'toString' in {}

…objects

Defined in: nodash.js, lines 751-770 (20 lines) • Show code

assign: function (/* ...objects */) {
  if (Object.assign) {
    // If the environment is capable of assign() then it can handle
    // symbols as well. If it isn't, then it doesn't support symbols
    // and we can iterate over objects manually.
    return Object.assign.apply(undefined, arguments)
  } else {
    var cur = arguments[0]
    var keys = {}
    for (var i = arguments.length - 1; i >= 1; i--) {
      Object.keys(arguments[i]).forEach(function (item, key) {
        if (!NoDash.hasOwn(keys, key)) {
          keys[key] = null
          cur[key] = item
        }
      })
    }
    return cur
  }
},
at ( value, path, def )

Returns value of value’s property or of its sub-objects.

Arguments
Name Types Notes
valuearray
object
patharray Each member is a key; resolving stops on null or undefined
scalar assume [path]
defmixed returned if property not found
omitted returns the last found undefined or null

Without def, it’s not possible to determine if path has resolved to a property with undefined and null or if it ended prematurely on such a property with more components left in path.

See also property() that returns a callback suitable for map().

Example
_.at('abc', 2)                          //=> 'c'
_.at('abc', -1)                         //=> 'c'
_.at(['a', 'b'], 1)                     //=> 'b'
_.at(['a', 'b'], [1])                   //=> 'b'
_.at({a: 1, b: 2}, 'b')                 //=> 2
_.at({a: 1, b: 2}, ['b'])               //=> 2

_.at(null, 0)                           //=> null
_.at(undefined, 0)                      //=> undefined
_.at(false, 0)                          //=> undefined = false[0]
_.at(false, 0, 'def')                   //=> 'def'

_.at([null], 0)                         //=> null
_.at([null], 0, 'def')                  //=> null
_.at([null], [0, 1])                    //=> null
_.at([null], [0, 1], 'def')             //=> 'def'
_.at([null], [1, 0])                    //=> undefined
_.at([null], [1, 0], 'def')             //=> 'def'

_.at({a: [{c: 123}]}}, ['a', 0, 'c'])   //=> 123
_.at({a: null}, ['a', 'b'])             //=> null
_.at({a: 123}, ['a', 'b'])              //=> undefined
_.at({}, ['a', 'b'])                    //=> undefined
_.at({a: undefined}, ['a'])             //=> undefined
_.at({a: undefined}, ['a'], 'def')      //=> undefined
_.at({}, ['a'], 'def')                  //=> 'def'
ExampleResolving dotted path notation (for example, used in template()):
_.at({prop: [{sub: true}]}, 'prop.0.sub'.split('.'))  //=> true
ExampleSince objects are unique, use a marker object for reliably determining lack of target property:
var notFound = {}
var value = _.at(obj, path, notFound)
if (value === notFound) { throw 'Property not found.' }

Defined in: nodash.js, lines 1862-1871 (10 lines) • Show code

at: function (value, path, def) {
  if (typeof path == 'string' || !NoDash.isArrayLike(path)) { path = [path] }
  for (var i = 0; i < path.length; i++) {
    if (value == null) {
      return (arguments.length > 2 && def !== unset) ? def : value
    }
    value = value[path[i]]
  }
  return value
},
bind ( func, cx , ...args )

Returns a version of func with added arguments and/or forced context.

Result Types
Types Notes
function
falsy if func or func[0] is falsy
Arguments
Name Types Notes
funcfunction (args are appended)
array of func[, cx[, ...hereArgs]] (cx and args arguments are ignored)
cxobject override the caller-specified context for func (its this)
undefined keep the caller-specified context
args Argument(s) pushed in front of the caller’s arguments to func

ECMAScript equivalent: o:Function/bind.

bind() is used for non-ES utilities like sortBy() to normalize the callback format for compatibility with Underscore, where some functions accept cx (un:findIndex), some accept arguments (un:defer), some accept nothing (e.g. un:throttle).

If your code depends strictly on NoDash then we recommend using a uniform way of specifying func as a single array value and forego function-specific cx/args.

If the context set by array func’s 1st member or, in absence of such, by cx is undefined then returned function preserves the caller-specified context (aka “partial” application).

Example
_.bind(function () { ... }, window, 'a').call(cx, 'b')
  // the function receives ('a', 'b') and its this = window
_.partial(function () { ... }, 'a').call(cx, 'b')
  // the function receive ('a', 'b') and its this = cx
// partial() is an alias, same as:
_.bind(function () { ... }, undefined, 'a').call(cx, 'b')

_.bind(f, cx, 'a2')('a1')
  //= f.call(cx, 'a2', 'a1')
_.bind([f], cx, 'a2')('a1')
  //= f.call(undefined, 'a1') - cx and 'a2' ignored
_.bind([f, window], cx, 'a2')('a1')
  //= f.call(window, 'a1') - here too
_.bind([f, window, 'a3'], cx, 'a2')('a1')
  //= f.call(window, 'a3', 'a1') - here too
_.bind([f, undefined, 'a3'], cx, 'a2')('a1')
  //= f('a3', 'a1') - preserving caller's context

, …args

Defined in: nodash.js, lines 1928-1930 (3 lines) • Show code

bind: function (func, cx /* , ...args */) {
  return bind(func, arguments, 1)
},
chunk ( value [, length] )

Splits value into chunks, all except last being length in size.

Result Types
Types Notes
array of arrays/objects/strings
Arguments
Name Types Notes
valuearray
object
string
lengthomitted = 1
int
Example
_.chunk('abcde')                //=> ['a', 'b', 'c', 'd', 'e']
  // same as 'abcde'.split('')
_.chunk('abcde', 2)             //=> ['ab', 'cd', 'e']
_.chunk([1, 2, 3, 4, 5], 2)     //=> [[1, 2], [3, 4], [5]]
_.chunk({a: 1, b: 2, c: 3}, 2)  //=> [{a: 1, b: 2}, {c: 3}]

Defined in: nodash.js, lines 1607-1619 (13 lines) • Show code

chunk: function (value, length) {
  value = NoDash.entries(value)
  var res = []
  while (value.length) {
    res.push(value.splice(0, length || 1))
  }
  if (NoDash.isArrayLike(value)) {
    res = NoDash.unzip(res)[1]
    return typeof value == 'string' ? res.join('') : res
  } else {
    return NoDash.fromEntries(res)
  }
},
compact ( value )

Returns a copy of value without falsy members.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object

See also filter(), reject(), partition().

Example
_.compact([null, '0', false])       //=> ['0']
_.compact({a: null, b: '', c: 1})   //=> {c: 1}

Defined in: nodash.js, lines 1406-1408 (3 lines) • Show code

compact: function (value) {
  return NoDash.filter(value, function (item) { return item })
},
countBy ( value, func, cx )

Calls func for every member of value, counting the number of times each result was returned.

Result Types
Types Notes
object
Arguments
Name Types Notes
valuearray
object
func Subject to bind(); receives member’s value, its key and the entire value; returns a scalar.
Example
_.countBy([-1, 1, 0, -2, 2], v => v > 0)
  //=> {false: 3, true: 2}
_.countBy({'0': 1, 0: 2, 1: 3}, (v, k) => k)
  //=> {'0': 1, 0: 1, 1: 1}
_.countBy({'0': 1, 0: 2, 1: 3}, (v, k) => +k)
  //=> {0: 2, 1: 1}

Defined in: nodash.js, lines 1281-1290 (10 lines) • Show code

countBy: function (value, func, cx) {
  func = bind(func, arguments, 2)
  var res = {}
  NoDash.forEach(value, function () {
    var group = func.apply(undefined, arguments)
    res[group] = res[group] || 0
    res[group]++
  }, cx)
  return res
},
debounce ( func, ms [, immediate] )

Returns a function that invokes func after ms after the last calling attempt.

Arguments
Name Types Notes
func Subject to bind()
msint
immediate If truthy, calls func immediately when called for the first time and then never calls for the subsequent ms

See also throttle().

ExampleIf ms is 100 and immediate is false, if the function is called, then called again after 50 ms, then again after 200 ms – func is called twice: after 100 ms after the 2nd call and after 100 ms after the 3rd call. If immediate is true, func is called right on the first call, then right on the 3rd.

Defined in: nodash.js, lines 1761-1780 (20 lines) • Show code

debounce: function (func, ms, immediate) {
  func = bind(func)
  var timer
  if (immediate) {
    return function () {
      if (!timer) {
        timer = setTimeout(function () { timer = null }, ms)
        return func.apply(this, arguments)
      }
    }
  } else {
    return function () {
      var args = [this, arguments]
      clearTimeout(timer)
      timer = setTimeout(function () {
        func.apply(args[0], args[1])
      }, ms)
    }
  }
},
defer ( func , ...args )

Calls func outside of the current call stack, giving it args.

from dl

Arguments
Name Types Notes
func Subject to bind()
msint

Calls delay() (mdn:WindowOrWorkerGlobalScope/setTimeout) with 0 delay.

Attention: the delay of 0 is not sufficient for certain operations, e.g. changes to a DOM node’s visual properties may be batched even across many defer()s unless a larger timeout (>= 20) is used.

, …args

Defined in: nodash.js, lines 1727-1731 (5 lines) • Show code

defer: function (func /* , ...args */) {
  var args = ap.slice.call(arguments)
  args.splice(1, 0, 0)
  return NoDash.delay.apply(undefined, args)
},
delay ( func, ms , ...args )

Calls func after a delay of ms, giving it args.

Arguments
Name Types Notes
funcdl Subject to bind()
msint

ECMAScript equivalent: mdn:WindowOrWorkerGlobalScope/setTimeout. See also defer().

, …args

Defined in: nodash.js, lines 1716-1718 (3 lines) • Show code

delay: function (func, ms /* , ...args */) {
  return setTimeout(bind(func, arguments, 2, true), ms)
},
difference ( value , ...values )

Returns members of the first argument that are not listed in other arguments.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuesarray
object first member’s value is kept
Example
_.difference([1, 2], [1, 3])               //=> [2]
_.difference({a: 1, b: 2}, {a: 3, c: 4})   //=> {b: 2}

, …values

Defined in: nodash.js, lines 1470-1477 (8 lines) • Show code

difference: function (value /* , ...values */) {
  var args = NoDash.sortBy(ap.slice.call(arguments, 1), NoDash.negate(NoDash.size, true))
  return NoDash.filter(value, function (item) {
    return !NoDash.some(args, function (a) {
      return a.includes(item)
    })
  })
},
endsWith ( value, sub [, endIndex] )

Returns true if value ends with sub.

from sw

Arguments
Name Types Notes
valuearray
object
string
subsame type as value Object keys are ignored; if empty, always returns true
endIndexomitted = length
int

ECMAScript equivalent: o:String/endsWith (not in IE). See also startsWith().

from swuo

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

Even though object can be given, doing so invokes undefined behaviour.

Example
_.endsWith('abc', 'bc')                 //=> true
_.endsWith('abc', 'ab', 2)              //=> true
_.endsWith(['ab', 'cd'], ['cd'])        //=> true
_.endsWith(['ab', 'cd'], ['ab', 'cd'])  //=> true
_.endsWith({a: 1, b: 2}, {c: 2})        //=> true
_.endsWith({a: 1, b: 2}, {b: 3})        //=> false

Defined in: nodash.js, lines 844-846 (3 lines) • Show code

endsWith: function (value, sub, endIndex) {
  return NoDash.startsWith(value, sub, endIndex, unset)
},
entries ( value )

Returns an array of arrays with key-value pairs for each member of value.

Result Types
Types Notes
array
Arguments
Name Types Notes
valuearray
object
string

ECMAScript equivalent: o:Object/entries (not in IE). See also fromEntries().

unordgenAttention: JavaScript objects are unordered.

entries() returns object value’s pairs in arbitrary order.

Example
_.entries(['a', 'b'])     //=> [[0, 'a'], [1, 'b']]
_.entries({a: 1, b: 2})   //=> [['a', 1], ['b', 2]]
_.entries('ab')           //=> [[0, 'a'], [1, 'b']]

Defined in: nodash.js, lines 664-674 (11 lines) • Show code

entries: function (value) {
  if (NoDash.isArrayLike(value)) {
    return NoDash.map(value, function (item, key) {
      return [key, item]
    })
  } else {
    return Object.keys(value).map(function (key) {
      return [key, value[key]]
    })
  }
},
escape ( value )

Replaces & < " ' in value with equivalent HTML entitites.

Result Types
Types Notes
array
object
string
Arguments
Name Types Notes
valuearray
object
string

The > is not escaped since it’s not special unless your markup is already broken (e.g. not using quotes for attributes). See https://mathiasbynens.be/notes/ambiguous-ampersands (thanks LoDash, lo:escape()).

Example
_.escape(' & < " \' > ')    //=> ' &amp; &lt; &quot; &#39; > '
_.escape(['a&b', '<c>d'])   //=> ['a&amp;b', '&lt;c>d']
_.escape({a: '"b\''})       //=> {a: '&quot;b&#39;'}
  • With jQuery you’d escape like so: $('<p>').text(value).html().
  • Not to be confused with standard o:escape() used for URL encoding.

Defined in: nodash.js, lines 963-970 (8 lines) • Show code

escape: function (value) {
  if (typeof value == 'string') {
    var to = {'&': 'amp', '<': 'lt', '"': 'quot', "'": '#39'}
    return value.replace(/&<"'/g, function (m) { return '&' + to[m] + ';' })
  } else {
    return NoDash.map(value, NoDash.escape)
  }
},
escapeRegExp ( str )

Returns a string with all chararcters special within RegExp delimiters prepended with a backslash.

Example
_.escapeRegExp('a.c*d-e')         //=> 'a\\.c\\*d\\-e'
new RegExp(_.escapeRegExp('*'))   //=> /\*/

Defined in: nodash.js, lines 977-980 (4 lines) • Show code

escapeRegExp: function (str) {
  // '-' in case escaping for a [character class], e.g. in trim*().
  return str.replace(/[-^$.*+?{}()[\]|\\]/g, '\\$&')
},
every ( value, func, cx )

Returns true if func returned truthyness for every member of value.

from fe

Arguments
Name Types Notes
valuearray
object
func Receives member’s value, its key and the entire value

ECMAScript equivalent: o:Array/every. See also some().

Example
_.every([1, 2, 3], v => v > 1)      //=> false
_.every({a: 1, b: 2}, v => v < 1)   //=> true
_.every('a-_@', v => /w/.test(v))   //=> false

Defined in: nodash.js, lines 373-377 (5 lines) • Show code

every: function (value, func, cx) {
  return transform(value, arguments, 1, ap.every, function () {
    return NoDash.findIndex(value, NoDash.negate(func), cx) === undefined
  })
},
fill ( value [, filler [, begin [, end]]] )

Returns a copy of value with values of members in the given range changed to filler.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object
fillermixed
beginint Starting index.
omitted = 0
endint Index of the member after last included in the result.
omitted = length

ECMAScript equivalent: o:Array/fill. See also repeat(), object().

from slend

Attention: slice(), o:String/substring() and fill() accept end as an index (exclusive!) while o:Array/splice() and o:String/substr() – as a length. Also, fill()’s end cannot be negative.

Example
_.fill([1, 2, 3], 'a', 0, -1)   //=> ['a', 'a', 3]
_.fill({a: 1, b: 2}, 'a')       //=> {a: 'a', b: 'a'}
ExampleArray’s constructor accepts new array’s length and creates a sparse Array where members are sort of undefined but can’t be iterated over except by some methods (e.g. o:Array/find). fill() can “un-sparse” it by assigning undefined till array’s length:
Array(3)                //=> [<3 empty slots>]
_.fill(Array(3))        //=> [undefined, undefined, undefined]
_.fill(Array(3), 'a')   //=> ['a', 'a', 'a']

Array(3).map(i => alert(i))
  // no alerts
Array(3).find(i => alert(i))
  // 3 alerts
_.fill(Array(3), 'a'),map(i => alert(i))
  // 3 alerts

Defined in: nodash.js, lines 629-644 (16 lines) • Show code

fill: function (value, filler, begin, end) {
  if (NoDash.isArrayLike(value) && ap.fill) {
    return ap.fill.call(value, filler, begin, end)
  } else {
    var isArray = NoDash.isArrayLike(value)
    value = NoDash.entries(value)
    begin = begin || 0
    if (arguments.length < 4) { end = Infinity }
    for (; begin < end && begin < value.length; ++begin) {
      value[begin][1] = filler
    }
    return isArray
      ? value.map(function (item) { return item[1] })
      : NoDash.fromEntries(value)
  }
},
filter ( value, func, cx )

Returns a copy of value without members for which func has returned falsyness.

Result Types
Types Notes
array
object

from fe

Arguments
Name Types Notes
valuearray
object
func Receives member’s value, its key and the entire value

ECMAScript equivalent: o:Array/filter. See also reject(), compact(), partition().

Example
_.filter([1, 2, 3], v => v > 1)       //=> [2, 3]
_.filter({a: 1, b: 2}, v => v > 1)    //=> {b: 2}
_.filter('a-_@', v => /\w/.test(v))   //=> ['a', '_']

Defined in: nodash.js, lines 352-363 (12 lines) • Show code

filter: function (value, func, cx) {
  return transform(value, arguments, 1, ap.filter, function () {
    var res = {}
    Object.keys(value).forEach(function (key) {
      var item = value[key]
      if (func.call(this, item, key, value)) {
        res[key] = item
      }
    }, cx)
    return res
  })
},
find ( value, func, cx )

Returns first member for which func has returned truthyness.

Result Types
Types Notes
mixed
undefined if not found

from fe

Arguments
Name Types Notes
valuearray
object
func Receives member’s value, its key and the entire value

ECMAScript equivalent: o:Array/find (not in IE). See also findIndex() that returns the key.

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

find() returns an arbitrary match if there are multiple matching object members.

Example
_.find(['a', 'bb', 'ccc'], v => v.length < 2)   //=> 'a'
_.find({a: 1, b: 2}, v => v < 2)        //=> 1

Defined in: nodash.js, lines 335-340 (6 lines) • Show code

find: function (value, func, cx) {
  var index = NoDash.findIndex.apply(undefined, arguments)
  // -1 can't occur for object, and if -1 then it's an array and so will
  // return undefined unless value has something at -1 index (unlikely).
  if (index !== undefined) { return value[index] }
},
findIndex ( value, func, cx )

Returns key of the first member of value for which func has returned truthyness.

Result Types
Types Notes
int for array value (-1 if not found)
scalar for object (undefined if not found)

from fe

Arguments
Name Types Notes
valuearray
object
func Receives member’s value, its key and the entire value

ECMAScript equivalent: o:Array/findIndex (not in IE). See also find() that returns the value.

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

findIndex() returns a key, not index for object value, and it returns an arbitrary match if there are multiple matching object members.

Example
_.findIndex(['a', 'b', 'c'], v => v == 'b')   //=> 1
_.findIndex({a: 1, b: 2}, v => v == 2)        //=> 'b'

Defined in: nodash.js, lines 305-321 (17 lines) • Show code

findIndex: function (value, func, cx) {
  var res = -1
  var iterator = function (item, key) {
    if (func.apply(this, arguments)) {
      res = key
      return true
    }
  }
  transform(value, [iterator, cx], 0, ap.some, function () {
    res = undefined
    // findIndex() is used by some() so it cannot call the latter.
    Object.keys(value).some(function (key) {
      return iterator.call(this, value[key], key, value)
    }, cx)
  })
  return res
},
first ( value [, length] )

Returns at most first length members of value.

Result Types
Types Notes
frmixed if length is omitted
array
object
Arguments
Name Types Notes
valuearray
object
lengthomitted return one member
int return a slice of value

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

This function returns arbitrary members for object value.

See also last(), initial(), rest().

Example
_.first(['ab', 'cd'])       //=> 'ab'
_.first(['ab', 'cd'], 1)    //=> ['ab']
_.first(['ab', 'cd'], 2)    //=> ['ab', 'cd']
_.first({a: 1, b: 2})       //=> 1

Defined in: nodash.js, lines 1082-1084 (3 lines) • Show code

first: function (value, length) {
  return slice(value, 0, arguments.length > 1 ? length : 1, arguments.length <= 1)
},
flat ( value [, depth] )

"Unwraps" nested arrays or objects in value.

Result Types
Types Notes
array
object with duplicate keys keeping arbitrary value
Arguments
Name Types Notes
valuearray Nested members of the same type are flattened: arrays in array, objects in object.
object
depthint Number of nesting levels to flatten; use Infinity to flatten all.
omitted = 1

ECMAScript equivalent: o:Array/flat (not in IE).

Example
_.flat([[[1]], {b: 2}, 3])      //=> [[1], {b: 2}, 3]
_.flat([[[1]], {b: 2}, 3], 2)   //=> [1, {b: 2}, 3]
_.flat({a: [1], b: {c: 3}})     //=> {a: [1], c: 3}

Defined in: nodash.js, lines 568-596 (29 lines) • Show code

flat: function (value, depth) {
  depth = depth || 1
  if (NoDash.isArrayLike(value)) {
    while (--depth >= 0) {
      value = ap.concat.apply([], value)
      // It's deemed faster to iterate over specific depths (which is
      // typically 1) even without changing value than checking every
      // member for array-likeness.
      if (depth == Infinity && !value.some(NoDash.isArrayLike)) {
        break
      }
    }
    return value
  } else {
    value = NoDash.entries(value)
    while (--depth >= 0) {
      var changed = false
      for (var i = value.length - 1; i >= 0; i--) {
        if (value[i][1] instanceof Object) {
          changed = value.splice(i, 1, NoDash.entries(value[i][1]))
        }
      }
      if (!changed) {
        break
      }
    }
    return NoDash.fromEntries(value)
  }
},
flip ( value )

Returns a copy of value with keys being former values and values being former keys.

Result Types
Types Notes
object
Arguments
Name Types Notes
valueobject
Example
_.flip({a: 1, b: 2})  //=> {1: 'a', 2: 'b'}
_.flip(['a', 'b'])    //=> {a: 0, b: 1}

Defined in: nodash.js, lines 1591-1594 (4 lines) • Show code

flip: function (value) {
  var unzipped = NoDash.unzip(NoDash.entries(value))
  return NoDash.object(unzipped[1], unzipped[0])
},
forEach ( value, func, cx )

Calls func for every member of value.

Result Types
Types Notes
undefined
Arguments
Name Types Notes
valuefearray
object
func Receives member’s value, its key and the entire value

ECMAScript equivalent: o:Array/forEach. See also invoke().

Example
var o = {}
_.forEach('abc', (char, index) => o.char = index)
  // o is {a: 0, b: 1, c: 2}

Defined in: nodash.js, lines 213-219 (7 lines) • Show code

forEach: function (value, func, cx) {
  return transform(value, arguments, 1, ap.forEach, function () {
    Object.keys(value).forEach(function (key) {
      func.call(this, value[key], key, value)
    }, cx)
  })
},
fromEntries ( value )

Returns an object constructed from arrays of key-value pairs.

Result Types
Types Notes
object
Arguments
Name Types Notes
valuearray
object

See also entries().

from unordgen

Attention: JavaScript objects are unordered.

“Order” of returned object’s keys won’t match order of pairs in value.

Example
_.entries([['a', 1], ['b', 2]])   //=> {a: 1, b: 2}
_.entries([[0, 'a'], [1, 'b']])   //=> {0: 'a', 1: 'b'}
ExampleGet an array or string result (their members will be in arbitrary order so you might want to sort() it):
_.toArray(_.fromEntries([[0, 'a'], [1, 'b']]))  //=> ['a', 'b']
_.toArray(_.fromEntries(...)).join('')          //=> 'ab'

Defined in: nodash.js, lines 692-698 (7 lines) • Show code

fromEntries: function (value) {
  var obj = {}
  NoDash.forEach(value, function (item) {
    obj[item[0]] = item[1]
  })
  return obj
},
groupBy ( value, func, cx )

Puts every member of value under its group determined by func.

Result Types
Types Notes
object Members are arrays or objects depending on value’s type.
Arguments
Name Types Notes
valuearray
object
func Subject to bind(); receives member’s value, its key and the entire value; returns a scalar (member’s group).

See also indexBy().

Example
_.groupBy([-1, 1, -2, 2], v => v > 0)
  //=> {false: [-1, -2], true: [1, 2]}
_.groupBy({x: 'ash', y: 'bosh'}, (v, k) => k[0])
  //=> {a: {x: 'ash'}, b: {y: 'bosh'}}

Defined in: nodash.js, lines 1232-1245 (14 lines) • Show code

groupBy: function (value, func, cx) {
  var isArray = NoDash.isArrayLike(value)
  func = bind(func, arguments, 2)
  var res = {}
  NoDash.forEach(value, function (item, key) {
    var group = func.apply(undefined, arguments)
    if (isArray) {
      ;(res[group] = res[group] || []).push(item)
    } else {
      ;(res[group] = res[group] || {})[key] = item
    }
  })
  return res
},
hasOwn ( value, property )

Returns true if value has defined property.

Arguments
Name Types Notes
value Any object type – Array, Function, etc.

ECMAScript equivalent: o:Object/hasOwnProperty. See also allKeys(), values().

Example
'toString' in {}
  //=> true (coming from Object.prototype)
_.hasOwn({}, 'toString')              //=> false
_.hasOwn({toString: f}, 'toString')   //=> true

'length' in []                        //=> true
_.hasOwn([], 'length')                //=> false

Defined in: nodash.js, lines 784-786 (3 lines) • Show code

hasOwn: function (value, property) {
  return Object.prototype.hasOwnProperty.call(value, property)
},
includes ( value, member [, fromIndex] )

Returns true if value contains member.

Arguments
Name Types Notes
valueinarray
object
string
fromIndexomitted = 0 If negative, searches from the end.
int

ECMAScript equivalent: o:Array/includes. See also indexOf().

Example
_.includes([5, 1, 3], 5)      //=> true
_.includes([5, 1, 3], 5, 1)   //=> false
_.includes([5, 1, 3], 3, -1)  //=> true
_.includes({a: 1, b: 2}, 2)   //=> true
_.includes('abc', 'bc', 1)     //=> true

Defined in: nodash.js, lines 428-430 (3 lines) • Show code

includes: function (value, member, fromIndex) {
  return NoDash.indexOf.apply(undefined, arguments) != -1
},
indexBy ( value, func, cx )

Changes keys of value members to ones determined by func.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object
func Subject to bind(); receives member’s value, its key and the entire value; returns a scalar (member’s new key); of duplicate keys only the last occurrence is kept (arbitrary for object value).

See also groupBy().

Example
_.indexBy([-1, 1, -2, 2], v => v > 0)
  //=> {false: -2, true: 2}
_.indexBy({x: 'ash', y: 'bosh'}, v => v[0])
  //=> {a: 'ash', b: 'bosh'}

Defined in: nodash.js, lines 1259-1266 (8 lines) • Show code

indexBy: function (value, func, cx) {
  func = bind(func, arguments, 2)
  var res = value.constructor()
  NoDash.forEach(value, function (item) {
    res[func.apply(undefined, arguments)] = item
  })
  return res
},
indexOf ( value, member [, fromIndex] )

Returns the key of first member appearing under value, or -1.

from in

Arguments
Name Types Notes
valuearray
object
string
fromIndexomitted = 0 If negative, searches from the end.
int

ECMAScript equivalent: o:Array/indexOf. See also includes(), lastIndexOf().

Example
_.indexOf([5, 1, 3], 5)      //=> 0
_.indexOf([5, 1, 3], 5, 1)   //=> -1
_.indexOf([5, 1, 3], 3, -1)  //=> 2
_.indexOf({a: 1, b: 2}, 2)   //=> 'b'
_.indexOf('abc', 'bc', 1)     //=> 1

Defined in: nodash.js, lines 444-460 (17 lines) • Show code

indexOf: function (value, member, fromIndex) {
  return transform(value, arguments, 1, ap.indexOf, function () {
    if (fromIndex < 0) {
      return NoDash.values(value).indexOf(member, fromIndex)
    } else {
      // Small optimization that avoids iterating/copying the entire
      // object as with values() when fromIndex is positive or not given
      // (object size is not required to be calculated beforehand).
      var index = NoDash.findIndex(value, function (item) {
        if (fromIndex === undefined || --fromIndex < 0) {
          return item === member
        }
      })
      return index === undefined ? -1 : index
    }
  })
},
initial ( value [, length] )

Returns all members of value except for last length.

Result Types
Types Notes
iniarray
object
Arguments
Name Types Notes
valuearray
object
lengthomitted = 1
int

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

See also last(), first(), rest().

Example
_.initial(['a', 'b', 'c'])      //=> ['a', 'b']
_.initial(['a', 'b', 'c'], 2)   //=> ['a']
_.initial({a: 1, b: 2, c: 3})   //=> {a: 1, b: 2}

Defined in: nodash.js, lines 1114-1116 (3 lines) • Show code

initial: function (value, length) {
  return slice(value, 0, arguments.length > 1 ? -length : -1, false)
},
intersection ( ...values )

Returns only members present in all given arguments.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuesarray
object first member’s value is kept

See also union(), assign().

Example
_.intersection([1, 2], [1, 3])               //=> [1]
_.intersection({a: 1, b: 2}, {a: 3, c: 4})   //=> {a: 1}

…values

Defined in: nodash.js, lines 1454-1461 (8 lines) • Show code

intersection: function (/* ...values */) {
  var args = NoDash.sortBy(arguments, NoDash.size)
  return NoDash.filter(args.shift(), function (item) {
    return NoDash.every(args, function (a) {
      return a.includes(item)
    })
  })
},
invoke ( value, method , ...args )

Treats every member of value as an object and calls method on it, returning results of all such calls.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object
methodstr
args Arguments that method’s receive, none by default.

See also forEach().

Example
_.invoke([' a', 'b '], 'trim')            //=> ['a', 'b']
_.invoke({a: 11, b: 29}, 'toString', 16)  //=> {a: 'b', b: '1d'}

, …args

Defined in: nodash.js, lines 1141-1146 (6 lines) • Show code

invoke: function (value, method /* , ...args */) {
  var args = ap.slice.call(arguments, 2)
  return NoDash.map(value, function (item) {
    return item[method].apply(item, args)
  })
},
isArguments ( value )

Returns true if value is the special Arguments object available inside functions.

Example
var f = function () { return _.isArguments(arguments) }
f()   //=> true

Defined in: nodash.js, lines 1009-1011 (3 lines) • Show code

isArguments: function (value) {
  return Object.prototype.toString.call(value) == '[object Arguments]'
},
isArrayLike ( value )

Returns true if value is an array-like object.

isArrayLike() is using the same criteria as ECMAScript’s o:Array/from, that is: a numeric length property.

See also isArray, toArray(), size().

Example
_.isArrayLike(null)           //=> false
_.isArrayLike([])             //=> true
_.isArrayLike('')             //=> true
_.isArrayLike(arguments)      //=> true
_.isArrayLike({})             //=> false
_.isArrayLike({length: 'z'})  //=> false
_.isArrayLike({length: -1})   //=> true

Defined in: nodash.js, lines 1000-1002 (3 lines) • Show code

isArrayLike: function (value) {
  return value && typeof value.length == 'number'
},
isElement ( value )

Returns true if value is a native DOM Element. See mdn:Node/nodeType.

Example
_.isElement(null)                           //=> false
_.isElement($('p'))                         //=> false
_.isElement(document.body)                  //=> true
_.isElement(document.createTextNode('z'))   //=> false

Defined in: nodash.js, lines 1033-1035 (3 lines) • Show code

isElement: function (value) {
  return value && value.nodeType === 1
},
isEmpty ( value )

Returns true if value has zero length or no keys (for non-isArrayLike objects).

Arguments
Name Types Notes
valuearray
object
Example
_.isEmpty([])           //=> true
_.isEmpty('')           //=> true
_.isEmpty({})           //=> true
_.isEmpty({length: 0})  //=> true
_.isEmpty({a: 1})       //=> false

Defined in: nodash.js, lines 1022-1024 (3 lines) • Show code

isEmpty: function (value) {
  return (NoDash.isArrayLike(value) ? value : Object.keys(value)).length < 1
},
join ( value, glue )

Returns a string consisting of stringified members of value separated by glue.

Result Types
Types Notes
str
Arguments
Name Types Notes
valuearray null and undefined members are seen as blank strings.
object
gluestr
undefined = ,

ECMAScript equivalent: o:Array/join.

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

join() combines object value’s members in arbitrary order.

Example
_.join([1, null, 3])        //=> 1,,3
_.join({a: 1, b: 2}, '-')   //=> 1-2

Defined in: nodash.js, lines 546-554 (9 lines) • Show code

join: function (value, glue) {
  return transform(value, arguments, 1, ap.join, function () {
    return Object.keys(value).map(function (key) {
      var item = value[key]
      return item == null ? '' : item
    })
      .join(glue === undefined ? ',' : glue)
  })
},
keys ( value )

Returns keys of members in value.

Result Types
Types Notes
array
Arguments
Name Types Notes
valuearray
object

ECMAScript equivalent: o:Object/keys. See also values().

Example
_.keys([1, 2])        //=> [0, 1]
_.keys(Array(3))      //=> [0, 1, 2]
_.keys({a: 1, b: 2})  //=> ['a', 'b']
_.keys('abc')         //=> [0, 1, 2]

Defined in: nodash.js, lines 709-713 (5 lines) • Show code

keys: function (value) {
  return transform(value, arguments, 0, function () {
    return NoDash.range(value.length)
  }, Object.keys)
},
last ( value [, length] )

Returns at most last length members of value.

from fr

Result Types
Types Notes
mixed if length is omitted
array
object
Arguments
Name Types Notes
valuearray
object
lengthomitted return one member
int return a slice of value

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

This function returns arbitrary members for object value.

See also first(), initial(), rest().

Example
_.last(['ab', 'cd'])       //=> 'cd'
_.last(['ab', 'cd'], 1)    //=> ['cd']
_.last(['ab', 'cd'], 2)    //=> ['ab', 'cd']
_.last({a: 1, b: 2})       //=> 2

Defined in: nodash.js, lines 1096-1098 (3 lines) • Show code

last: function (value, length) {
  return slice(value, arguments.length > 1 ? -length : -1, undefined, arguments.length <= 1)
},
lastIndexOf ( value, member [, fromIndex] )

Returns the key of last member appearing under value, or -1.

from in

Arguments
Name Types Notes
valuearray
object
string
fromIndexomitted = 0 If negative, searches from the end.
int

ECMAScript equivalent: o:Array/lastIndexOf. See also indexOf().

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

lastIndexOf() returns key of arbitrary member’s occurrence just like indexOf().

Example
_.lastIndexOf([1, 2, 1], 1)     //=> 2
_.lastIndexOf([1, 2, 1], 2, 2)  //=> -1
_.indexOf({a: 1, b: 1}, 2)      //=> 'b'
_.indexOf('bba', 'ba', 1)       //=> 1

Defined in: nodash.js, lines 477-481 (5 lines) • Show code

lastIndexOf: function (value, member, fromIndex) {
  return transform(value, arguments, 1, ap.lastIndexOf, function () {
    return NoDash.values(value).lastIndexOf(member, fromIndex)
  })
},
map ( value, func, cx )

Returns a copy of value with values replaced by results of calling func’s for each member.

Result Types
Types Notes
array
object

from fe

Arguments
Name Types Notes
valuearray
object
func Receives member’s value, its key and the entire value

ECMAScript equivalent: o:Array/map. See also pluck().

Example
_.map([1, 2], v => v * 2)               //=> [2, 4]
_.map({a: 1, b: 2}, v => v * 2)         //=> {a: 2, b: 4}
_.map('\1\2\3', v => v.charCodeAt(0))   //=> [1, 2, 3]

Defined in: nodash.js, lines 230-238 (9 lines) • Show code

map: function (value, func, cx) {
  return transform(value, arguments, 1, ap.map, function () {
    var res = {}
    NoDash.forEach(value, function (v, k) {
      res[k] = func.apply(this, arguments)
    }, cx)
    return res
  })
},
max ( value [, func [, cx]] )

Returns the “maximum” member as ranked by func.

Result Types
Types Notes
mixed
-Infinity if value is empty
Arguments
Name Types Notes
valuemxarray
object
funcomitted take the member’s value as its rank Subject to bind(); receives member’s value, its key and the entire value; returns a comparable (number or string).
function

ECMAScript equivalent: o:Math/max. See also min(),

Example
_.max([1, 2, 3])            //=> 3
_.max({a: 1, b: 2})         //=> 2
_.max([1, 2, 3], v => -v)   //=> 1 (ranked as -1, others as -2, -3)

Defined in: nodash.js, lines 1176-1192 (17 lines) • Show code

max: function (value, func, cx) {
  if (!func && NoDash.isArrayLike(value)) {
    return Math.max.apply(undefined, value)
  } else {    // if func or (!func and non-array).
    var max = -Infinity
    var maxItem = -Infinity
    func = bind(func, arguments, 2)
    NoDash.forEach(value, function (item) {
      var num = func ? func.apply(this, arguments) : item
      if (num > max) {
        max = num
        maxItem = item
      }
    })
    return maxItem
  }
},
min ( value [, func [, cx]] )

Returns the “minimum” member as ranked by func.

Result Types
Types Notes
mixed
+Infinity if value is empty

from mx

Arguments
Name Types Notes
valuearray
object
funcomitted take the member’s value as its rank Subject to bind(); receives member’s value, its key and the entire value; returns a comparable (number or string).
function

ECMAScript equivalent: o:Math/min. See also max(),

Defined in: nodash.js, lines 1198-1204 (7 lines) • Show code

min: function (value, func, cx) {
  func = bind(func, arguments, 2)
  var res = NoDash.max(value, function (value) {
    return -(func ? func.apply(undefined, arguments) : value)
  })
  return res === -Infinity ? Infinity : res
},
negate ( func [, numeric] )

Returns a function that calls func and inverts its result.

Arguments
Name Types Notes
func Subject to bind()
numeric If truthy, changes sign of func’s result, else treats it as bool.
Example
_.negate(() => true)      //=> will return false
_.negate(() => -1, true)  //=> will return +1

Defined in: nodash.js, lines 1045-1051 (7 lines) • Show code

negate: function (func, numeric) {
  func = bind(func)
  return function () {
    var res = func.apply(this, arguments)
    return numeric ? -res : !res
  }
},
noConflict ( )

When NoDash is used outside of a module, restores old value of global _ and returns the NoDash object.

Defined in: nodash.js, line 195

object ( keys [, values] )

Returns an object constructed from given keys and values as separate lists.

Result Types
Types Notes
object
Arguments
Name Types Notes
keysarray
object
valuessame type as keys Missing member for keys assumes undefined, extra member is unused.
omitted

If keys/values are objects, their existing keys are ignored.

See also fill(), repeat().

Example
_.object(['a', 'b'])          //=> {a: undefined, b: undefined}
_.object(['a', 'b'], ['z'])   //=> {a: 'z', b: undefined}
_.object(['a', 'b'], ['z', 'y', 'x'])   //=> {a: 'z', b: 'y'}
_.object({a: 1, b: 2}, {c: 3, d: 4})    //=> {1: 3, 2: 4}

Defined in: nodash.js, lines 1573-1582 (10 lines) • Show code

object: function (keys, values) {
  if (NoDash.isArrayLike(keys)) {
    var zipped = NoDash.zip(keys, values || [])
  } else {
    values = values || {}
    var zipped = Object.keys(NoDash.assign.apply(undefined, arguments))
      .map(function (key) { return [keys[key], values[key]] })
  }
  return NoDash.fromEntries(zipped)
},
omit ( value, func [, cx] | value, keys | value, ...keys )

Returns members of value with mismatching keys.

from pk

function (value, func[, cx])        // matching each member by callback
function (value, keys)              // keys given as an array
function (value, key[, key, ...])   // keys given directly as arguments

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object
func Given to filter(); this call form exists for compatibility with Underscore’s un:pick() where filter() cannot work on objects.

See also pick() that returns matching keys.

Example
_.omit({a: 1, b: 2, c: 3}, v => v < 2)    //=> {b: 2, c: 3}
_.omit({a: 1, b: 2, c: 3}, ['a', 'c'])    //=> {b: 2}
_.omit({a: 1, b: 2, c: 3}, 'a', 'c')      //=> {b: 2}
_.omit(['a', 'b', 'c'], 1, 3)             //=> ['b']

Defined in: nodash.js, lines 1705-1707 (3 lines) • Show code

omit: function (value, func, cx) {
  return NoDash.reject(value, pickerFunction(func, arguments, 1), cx)
},
once ( func )

Returns a function that invokes func once, remembers its return value and returns it for subsequent calls without invoking func again.

Arguments
Name Types Notes
func Subject to bind()

once() can be used for memoization, i.e. caching result of a heavy operation.

Example
var f = _.once(() => Math.random())
f()   //=> 0.2446989
f()   //=> 0.2446989

Defined in: nodash.js, lines 1791-1799 (9 lines) • Show code

once: function (func) {
  var res = unset
  return function () {
    if (res === unset) {
      res = bind(func).apply(this, arguments)
    }
    return res
  }
},
padEnd ( value, length [, pad] )

Returns a copy of value, with appended pad if its length was too short.

from ps

Result Types
Types Notes
array Always shallow-copied, even if value was long enough.
string
Arguments
Name Types Notes
valuearray
string
lengthint Desired returned value’s length.
padmixed for array value
string for string value
omitted = undefined or ' '

ECMAScript equivalent: o:String/padEnd (not in IE). See also padStart().

Example
_.padEnd('abc', 5)        //=> 'abc  '
_.padEnd('abcdef', 5)     //=> 'abcdef'
_.padEnd('abc', 5, 'z')   //=> 'abczz'
_.padEnd([], 3)           //=> [undefined, undefined, undefined]
_.padEnd(['a'], 3, 'z')   //=> ['a', 'z', 'z']

Defined in: nodash.js, lines 891-893 (3 lines) • Show code

padEnd: function (value, length, pad) {
  return NoDash.padStart(value, length, pad, unset)
},
padStart ( value, length [, pad] )

Returns a copy of value, with prepended pad if its length was too short.

Result Types
Types Notes
psarray Always shallow-copied, even if value was long enough.
string
Arguments
Name Types Notes
valuearray
string
lengthint Desired returned value’s length.
padmixed for array value
string for string value
omitted = undefined or ' '

ECMAScript equivalent: o:String/padStart (not in IE). See also padEnd().

Example
_.padStart('abc', 5)        //=> '  abc'
_.padStart('abcdef', 5)     //=> 'abcdef'
_.padStart('abc', 5, 'z')   //=> 'zzabc'
_.padStart([], 3)           //=> [undefined, undefined, undefined]
_.padStart(['a'], 3, 'z')   //=> ['z', 'z', 'a']

Defined in: nodash.js, lines 867-876 (10 lines) • Show code

padStart: function (value, length, pad, end) {
  var add = Math.max(0, length - NoDash.size(value))
  if (typeof value == 'string') {
    if (arguments.length < 3) { pad = ' ' }
    pad = Array(add + 1).join(pad).substr(0, add)
  } else {
    pad = NoDash.fill(Array(add), pad)
  }
  return end === unset ? value.concat(pad) : pad.concat(value)
},
partition ( value, func, cx )

Splits members of value into two groups determined by func.

Result Types
Types Notes
array of matching, mismatching where each member is either an array or object depending on value’s type
Arguments
Name Types Notes
valuearray
object
func Subject to bind(); receives member’s value, its key and the entire value; result converted to bool.

See also filter(), reject(), compact().

Example
_.partition([-1, 1, -2, 2], v => v > 0)
  //=> [[1, 2], [-1, -2]]
_.partition({a: -1, b: 2}, v => v > 0)
  //=> [{b: 2}, {a: -1}]

Defined in: nodash.js, lines 1385-1397 (13 lines) • Show code

partition: function (value, func, cx) {
  func = bind(func, arguments, 2)
  var isArray = NoDash.isArrayLike(value)
  var mismatching = isArray ? [] : {}
  var matching = NoDash.filter(value, function (item, key) {
    if (func.apply(this, arguments)) {
      return true
    } else {
      isArray ? mismatching.push(item) : (mismatching[key] = item)
    }
  })
  return [matching, mismatching]
},
pick ( value, func [, cx] | value, keys | value, ...keys )

Returns members of value with matching keys.

pk

function (value, func[, cx])        // matching each member by callback
function (value, keys)              // keys given as an array
function (value, key[, key, ...])   // keys given directly as arguments

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object
func Given to filter(); this call form exists for compatibility with Underscore’s un:pick() where filter() cannot work on objects.

See also omit() that returns mismatching keys.

Example
_.pick({a: 1, b: 2, c: 3}, v => v < 2)    //=> {a: 1}
_.pick({a: 1, b: 2, c: 3}, ['a', 'c'])    //=> {a: 1, c: 3}
_.pick({a: 1, b: 2, c: 3}, 'a', 'c')      //=> {a: 1, c: 3}
_.pick(['a', 'b', 'c'], 1, 3)             //=> ['a', 'c']

Defined in: nodash.js, lines 1691-1693 (3 lines) • Show code

pick: function (value, func, cx) {
  return NoDash.filter(value, pickerFunction(func, arguments, 1), cx)
},
pluck ( value, property )

Treats every emmber of value as an object and collects their property.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object

See also map().

Example
_.pluck(['ab', 'ccdd'], 'length')         //=> [2, 4]
_.pluck({a: 'ab', b: 'ccdd'}, 'length')   //=> {a: 2, b: 4}

Defined in: nodash.js, lines 1155-1159 (5 lines) • Show code

pluck: function (value, property) {
  return NoDash.map(value, function (obj) {
    return obj[property]
  })
},
property ( path, def )

Returns a function accepting an object and returning value of its property or of its sub-objects.

property() calls at() on the inside.

Example
var objects = [{a: 'abc'}, {a: 'def'}]
_.map(objects, _.property(['a', 1]))    //=> ['b', 'e']

Defined in: nodash.js, lines 1808-1811 (4 lines) • Show code

property: function (path, def) {
  if (arguments.length < 2) { def = unset }
  return function (value) { return NoDash.at(value, path, def) }
},
random ( [[min, ] max] )

Returns a random number.

Arguments
Name Types Notes
() Returns a float between 0 (inclusive) and 1 (exclusive).
max Returns an int between 0 and max (inclusive).
min_max Returns an int between min and max (inclusive).

ECMAScript equivalent: o:Math/random.

Defined in: nodash.js, lines 1323-1332 (10 lines) • Show code

random: function (min, max) {
  switch (arguments.length) {
    case 0:
      return Math.random()
    case 1:
      return NoDash.random(0, min)
    default:
      return min + Math.floor(Math.random() * (max - min + 1))
  }
},
range ( [begin, ] end [, step] )

Returns an array of numbers, each different by step.

Arguments
Name Types Notes
end If negative, returns a series from end (exclusive) to 0 (inclusive), else from 0 (inclusive) to end (exclusive).
begin_end Returns a series from begin (inclusive) to end (exclusive).
...stepint non-zero Defaults to -1 or +1 depending on begin and end

See also times().

Example
_.range(0)        //=> []
_.range(3)        //=> [0, 1, 2]
_.range(-3)       //=> [-2, -1, 0]
_.range(2, 5)     //=> [2, 3, 4]
_.range(5, 2)     //=> [5, 4, 3]
_.range(2, 5, 2)  //=> [2, 4]

Defined in: nodash.js, lines 1636-1648 (13 lines) • Show code

range: function (begin, end, step) {
  switch (arguments.length) {
    case 1:
      return begin > 0 ? NoDash.range(0, begin) : NoDash.range(begin, 1)
    case 2:
      step = begin > end ? -1 : +1
    default:
      return NoDash.fill(Array(Math.floor((end - begin - 1) / step) || 0))
        .map(function () {
          return (begin += step) - step
        })
  }
},
reduce ( value, func [, initial )

Calls func for every member of value, returning result of the last call.

Result Types
Types Notes
rdmixed as returned by func
Arguments
Name Types Notes
valuearray
object
func Receives result of the previous func call, member’s value, its key and the entire value
initialomitted If omitted, func is not called for the first time; instead, that member’s value is used as if it was returned by func
mixed

ECMAScript equivalent: o:Array/reduce. See also reduceRight() that iterates from the end of value.

Example
_.reduce([1, 2, 3], (memo, v) => memo + v)      //=> 1 + 2 + 3
_.reduce([1, 2, 3], (memo, v) => memo + v, -1)  //=> -1 + 1 + 2 + 3

Defined in: nodash.js, lines 256-270 (15 lines) • Show code

reduce: function (value, func, initial) {
  var setInitial = arguments.length < 3
  return transform(value, arguments, 1, ap.reduce, function () {
    var memo = initial
    NoDash.forEach(value, function (v, k) {
      if (setInitial) {
        memo = v
        setInitial = false
      } else {
        memo = func.call(undefined, memo, v, k, value)
      }
    })
    return memo
  })
},
reduceRight ( value, func [, initial )

Calls func for every member of value starting from the last member, returning result of the last call.

from rd

Result Types
Types Notes
mixed as returned by func
Arguments
Name Types Notes
valuearray
object
func Receives result of the previous func call, member’s value, its key and the entire value
initialomitted If omitted, func is not called for the first time; instead, that member’s value is used as if it was returned by func
mixed

ECMAScript equivalent: o:Array/reduceRight. See also reduce() that iterates from the start of value.

unorderedAttention: be wary about object value – JavaScript objects are unordered.

reduceRight() goes over value in any order just like reduce().

Defined in: nodash.js, lines 284-288 (5 lines) • Show code

reduceRight: function (value, func, initial) {
  return transform(value, arguments, 1, ap.reduceRight, function () {
    return NoDash.reduce(NoDash.reverse(value), func, initial)
  })
},
reject ( value, func, cx )

Returns a copy of value without members for which func has returned truthyness.

Result Types
Types Notes
array
object

from fe

Arguments
Name Types Notes
valuearray
object
func Receives member’s value, its key and the entire value

See also filter(), compact(), partition().

Since reject() is non-standard, its func is subject to bind() but it’s better not to rely on this for symmetry and in case it gets standardized.

Defined in: nodash.js, lines 1061-1063 (3 lines) • Show code

reject: function (value, func, cx) {
  return NoDash.filter(value, NoDash.negate(func), cx)
},
repeat ( value, count )

Returns copies of value duplicated count times.

Result Types
Types Notes
array
string
Arguments
Name Types Notes
valuearray
string

ECMAScript equivalent: o:String/repeat (not in IE). See also fill().

Example
_.repeat('ab', 3)             //=> 'ababab'
_.repeat(['ab', 'cd'], 3)     //=> ['ab', 'cd', 'ab', 'cd', 'ab', 'cd']
_.repeat([['ab', 'cd']], 2)   //=> [['ab', 'cd'], ['ab', 'cd']]

Defined in: nodash.js, lines 904-906 (3 lines) • Show code

repeat: function (value, count) {
  return value.concat.apply(value.constructor(), NoDash.fill(Array(count), value))
},
rest ( value [, length] )

Returns all members of value except for first length.

from ini

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object
lengthomitted = 1
int

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

See also first(), last(), initial().

Example
_.rest(['a', 'b', 'c'])      //=> ['b', 'c']
_.rest(['a', 'b', 'c'], 2)   //=> ['c']
_.rest({a: 1, b: 2, c: 3})   //=> {b: 2, c: 3}

Defined in: nodash.js, lines 1127-1129 (3 lines) • Show code

rest: function (value, length) {
  return slice(value, arguments.length > 1 ? length : 1, undefined, false)
},
reverse ( value )

Returns the copy of values with members in reverse order.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object

ECMAScript equivalent: o:Array/reverse.

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

It probably makes no sense to use reverse() on an object value.

Example
_.reverse([5, 1, 3])      //=> [3, 1, 5]
_.reverse({a: 1, b: 2})   //=> {b: 2, a: 1}

Defined in: nodash.js, lines 523-531 (9 lines) • Show code

reverse: function (value) {
  return transform(value, [], 0, ap.reverse, function () {
    var res = {}
    Object.keys(value).reverse().forEach(function (key) {
      res[key] = value[key]
    })
    return res
  })
},
shuffle ( value [, length] )

Returns a copy of value with at most length random members.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object
lengthomitted = length
int

See also sample() that returns a single item.

Example
_.shuffle([1, 2, 3])              //=> [3, 1, 2]
_.shuffle([1, 2, 3], 1)           //=> [2]
_.shuffle([1, 2, 3], 2)           //=> [2, 1]
_.shuffle({a: 1, b: 2, c: 3}, 2)  //=> {b: 2, a: 1}

Defined in: nodash.js, lines 1303-1316 (14 lines) • Show code

shuffle: function (value, length) {
  if (arguments.length < 2) { length = value.length }
  var sized = NoDash.size(value)
  var isArray = NoDash.isArrayLike(value)
  value = isArray ? ap.slice.call(value) : NoDash.entries(value)
  for (var i = 0; i < sized && i < length; i++) {
    var j = NoDash.random(sized - 1)
    var temp = value[i]
    value[i] = value[j]
    value[j] = temp
  }
  value.splice(length)
  return isArray ? value : NoDash.fromEntries(value)
},
size ( value )

Returns number of members in value.

Arguments
Name Types Notes
valuearray
object
string

See also isArrayLike().

Example
_.size('abc')                     //=> 3
_.size(['a', 'b'])                //=> 2
_.size({a: 1, b: 2})              //=> 2
_.size({a: 1, b: 2, length: 5})   //=> 5

Defined in: nodash.js, lines 1365-1371 (7 lines) • Show code

size: function (value) {
  if (NoDash.isArrayLike(value)) {
    return value.length
  } else {
    return Object.keys(value).length
  }
},
slice ( value [, begin [, end]] )

Returns a portion of value.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object
beginslbeint Starting index.
omitted = 0
endint Index of the member after last included in the result; if negative set to length - end (hence give -1 to omit last member).
omitted = length

ECMAScript equivalent: o:Array/slice.

slendAttention: slice(), o:String/substring() and fill() accept end as an index (exclusive!) while o:Array/splice() and o:String/substr() – as a length. Also, fill()’s end cannot be negative.

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

slice() returns arbitrary members for object value.

Example
_.slice('abc', 0, 2)          //=> 'ab'
_.slice([1, 2, 3], 1)         //=> [2, 3]
_.slice({a: 1, b: 2}, 0, 1)   //=> {a: 1}

Defined in: nodash.js, lines 507-511 (5 lines) • Show code

slice: function (value, begin, end) {
  return transform(value, arguments, 1, ap.slice, function () {
    return NoDash.fromEntries(NoDash.entries(value).slice(begin, end))
  })
},
some ( value, func, cx )

Returns true if func returned truthyness for any member of value.

from fe

Arguments
Name Types Notes
valuearray
object
func Receives member’s value, its key and the entire value

ECMAScript equivalent: o:Array/some. See also every().

Example
_.some([1, 2, 3], v => v > 1)      //=> true
_.some({a: 1, b: 2}, v => v < 1)   //=> false
_.some('a-_@', v => /w/.test(v))   //=> true

Defined in: nodash.js, lines 387-391 (5 lines) • Show code

some: function (value, func, cx) {
  return transform(value, arguments, 1, ap.some, function () {
    return NoDash.findIndex(value, func, cx) !== undefined
  })
},
sort ( value, func )

Returns a copy of value with members sorted according to func.

Result Types
Types Notes
array Even for object value
Arguments
Name Types Notes
valuearray
object
func Receives av, bv, ak, bk and should return a positive value if av must appear after bv, negative if before, or zero if they may appear in any order (makes sorting unstable); ak and bk are their keys within value and are only not given for object value

ECMAScript equivalent: o:Array/sort. See also sortBy()

Example
_.sort([5, 1, 3], (a, b) => a - b)      //=> [1, 3, 5]
_.sort({a: 5, b: 2}, (a, b) => a - b)   //=> [2, 5]

Defined in: nodash.js, lines 404-412 (9 lines) • Show code

sort: function (value, func) {
  return transform(value, arguments, 1, ap.sort, function () {
    return NoDash.entries(value)
      .sort(function (a, b) {
        return func.call(undefined, a[1], b[1], a[0], b[0])
      })
      .map(function (item) { return item[1] })
  })
},
sortBy ( value, func, cx )

Returns a copy of value with members sorted according to func.

Result Types
Types Notes
array Even for object value
Arguments
Name Types Notes
valuearray
object
func Subject to bind(); receives member’s value, its key and the entire value; returns a comparable (number or string); members with identical ranks are sorted by their keys.

See also sort()

Example
_.sort([5, 1, 3], v => v)               //=> [1, 3, 5]
_.sort({a: 5, b: 2}, (v, k) => k)       //=> {a: 5, b: 2}

Defined in: nodash.js, lines 1216-1219 (4 lines) • Show code

sortBy: function (value, func, cx) {
  var entries = tagAndSort(value, func, cx)
  return entries.map(function (item) { return item[1] })
},
startsWith ( value, sub [, startIndex] )

Returns true if value begins with sub.

Arguments
Name Types Notes
valueswarray
object
string
subsame type as value Object keys are ignored; if empty, always returns true
startIndexomitted = 0
int

ECMAScript equivalent: o:String/startsWith (not in IE). See also endsWith().

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

Even though object can be given, doing so invokes undefined behaviour.

Example
_.startsWith('abc', 'ab')                 //=> true
_.startsWith('abc', 'bc', 1)              //=> true
_.startsWith(['ab', 'cd'], ['ab'])        //=> true
_.startsWith(['ab', 'cd'], ['ab', 'cd'])  //=> true
_.startsWith([{}], [{}])                  //=> false ({} !== {})
_.startsWith({a: 1, b: 2}, {c: 1})        //=> true
_.startsWith({a: 1, b: 2}, {a: 3})        //=> false

Defined in: nodash.js, lines 816-826 (11 lines) • Show code

startsWith: function (value, sub, startIndex, ends) {
  if (!NoDash.isArrayLike(value)) { sub = NoDash.values(sub) }
  var length = sub.length
  var part = ends === unset
    ? NoDash.slice(value, startIndex - length, startIndex)
    : NoDash.slice(value, startIndex, startIndex + length)
  return NoDash.size(part) == length &&
    NoDash.every(NoDash.values(part), function (item, index) {
      return item === sub[index]
    })
},
template ( str, options )

Converts a template str to a function that accepts variables and returns a formatted string.

Result Types
Types Notes
function accepting vars, opts See below.
Arguments
Name Types Notes
strstring The template.
function take the contents of the first /**/ comment
Node take textContent
optionsobject Compilation options.
omitted

Possible options keys:

Arguments
Name Types Notes
prepareobject defaults for formatting variables and/or options (under o)
function receives caller-given vars, opt (as {} if falsy) and returns an object with complete variables and options (may be mutated)
omitted
withbool If set, members of vars can be referenced directly, not through v; such templates are slower due to using JavaScript’s with { }; non-code ref work regardless of this (v is added automatically).
null enable only if there exists a code ref
laxRefbool If set, non-code ref are resolved with property(), meaning they return the non-object value immediately, even if there are more path components (that triggers an error without laxRef, but is faster).
omitted = true
evalbool If unset, fails to compile if there are constructs allowing arbitrary code execution; in such case it should be safe to pass str from untrusted input since it can only operate on values given to the compiled function (unless there are custom blocks).
omitted = true
blocksobject New custom or overridden standard if/for/etc.; key is the block’s name (alphanumeric), value is a function receiving param, value, c:
Arguments
Name Types Notes
paramfalse if no :... given Part after :; false conveniently is '' for cases when block and block: are identical.
str
valuefalse no space given Part after space; on conflict with non-code echo the latter wins so add a colon for unambiguity: {{echo}} but {{block:}}
str
cobj Current compiler’s state; keys:
Arguments
Name Types Notes
optionsobj An internal copy of options given to template(), with filled defaults.
reffunction Receives a raw string, returns a JavaScript code snippet evaluating to string.
stack Current chain of blocks, first being last opened.
* Other keys can be used for storing custom state data.

Attention: be mindful of operator precedence: returning code like a || b will prevent the template from running; instead, return (a || b). Brackets are not added automatically because ( may appear in start and a matching ) appears in end.

Function must return an object with keys:

Arguments
Name Types Notes
startomitted JavaScript code evaluating to string.
str
endomitted JavaScript code evaluating to string at the time block’s end is met ({{/}}); if null then the block isn’t opened and needs not be closed (alike to <input> in HTML).
str
typeomitted Used together with end; sets matching block_end’s type; defaults for the block’s key.
str
headomitted JavaScript code added to the beginning of the compiled function; useful for declaring variables.
str
omitted = default if/for/etc.

Template syntax loosely resembles that of Mustache.js/Handlebars.js - all substitutions are performed within {{...}}:

escaped       = \[\\...]{{
echo          = {{ [=] ref }}
conditional   = {{ [else]if[:not] ref }}
              | {{ else[:] }}
loop          = {{ for[:[pf]] ref }}
              | {{ elseif[:pf|-[:not]] ref }}
              | {{ else[:pf|-] }}
block_end     = {{ / [if|for] }}
custom        = {{ key[:[param]][ value] }}
              | {{ / [key] }}

ref           = var[.prop...] | code

  • escaped: a pair of { prefixed with odd number of \ becomes raw {{ prefixed with half that number of \; even number of \ doesn’t escape {{ but is still emitted “halved”:
    \{{ = {{    \\\{{ = \{    \\\\\{{ = \\{{
    \\{{...}} = \ + result    \\\\{{...}} = \\ + result
  • echo: emits value of a variable/property (not of global like window) or result of executing arbitrary code (if ref is not alphanumeric with periods). Without = the result is post-processed by o.escaper (e.g. HTML-escaped). If ref is falsy, emits nothing.
  • conditional: emits the enclosed block only if ref is truthy (falsy with :not).
  • loop: emits the enclosed block once for every iteration. ref is given to forEach(). Optional pf specifies prefix for variables inside the block that are by default v (value), k (key), i (index, same as k if ref isArrayLike), vv (the ref).

    Only i exists outside of the block and is undefined prior to the first loop with that pf; after a loop it holds index of the last iterated member, or -1 if ref was empty – this is what loop’s enclosed elseif/else test (they also change for’s block_end from /for to /if). Without : or with :-, last for (its pf) is checked: {{elseif}} {{elseif:-}} {{elseif:-:not}} – but here last for with empty pf is checked: {{elseif:}} {{elseif::not}}.

  • block_end: give the expected block’s type (not simply {{/}}) for extra syntax safety:
    {{if ...}} {{for ...}} {{/}} {{/}}        - works
    {{if ...}} {{for ...}} {{/for}} {{/if}}   - works
    {{if ...}} {{for ...}} {{/if}} {{/for}}   - fails to compile
  • Nesting {{ }} is not supported but you can use string escapes: {{'}}'}} fails but {{'\x7d}'}} works.

The returned compiled template function accepts these arguments:

Arguments
Name Types Notes
vobject Variables for access by ref
falsy = {}
oobject Formatting options; standard keys:
Arguments
Name Types Notes
escaperfunction echo without = runs the value through this; in HTML context you’d set it to escape()
omitted return as is
falsy = {}

These variables exist within the returned function:

Arguments
Name Types Notes
_ Reference to NoDash regardless of the global _
v Variables as given by the caller.
o Options as given by the caller.
* Members of v, if options.with is set.
Example
_.template('{{a.b.c}}')({})                   //=> ''
_.template('{{a.b.c}}', {laxRef: false})      // Error
_.template('{{Math.random()}}')()             //=> 0.2446989

_.template('{{if Math.random() > 0.5}}win!{{/}}')()
  //=> 'win!' or ''
_.template('{{if Math.random > 0.5}}win!{{/}}')()
  // Error (laxRef only affects non-code ref)
_.template('{{if Math.random > 0.5}}win!{{/}}')({
  Math: {random: 9000},
})
  //=> 'win!'

_.template('{{if Math.random}}win!{{/}}')({}, {laxRef: false})
  // Error
_.template('{{if Math.random}}win!{{/}}')()
  //=> ''
_.template('{{if:not Math.random}}win!{{/}}')()
  //=> 'win!'
_.template('{{if Math.random}}win!{{/}}')({
  Math: {random: 0},
})
  //=> ''
_.template('{{if Math.random}}win!{{/}}')({
  Math: {random: -451},
})
  //=> 'win!'

_.template('{{document.title}}')()            //=> ''
_.template('{{document.title}}')({
  document: {title: 'foo'},
})
  //=> 'foo'
_.template('{{document.title}}')({
  document: {title: 'foo'},
}, {with: false})
  //=> 'foo'
_.template('{{document['title']}}')()
  //=> 'bar' (window.document.title)
_.template('{{document['title']}}')({
  document: {title: 'foo'},
})
  //=> 'foo'
_.template('{{document['title']}}')({
  document: {title: 'foo'},
}, {with: false})
  //=> 'bar'
Example
var tpl = function () { /*
  {{if homepage}}<a href="{{homepage}}">Homepage</a>{{/}}
*/ }
_.template(tpl)({homepage: 'https://squizzle.me'})
  //=> <a href="https://squizzle.me">Homepage</a>
ExampleGiven this node somewhere in DOM (<template> is unsupported in IE):
<script type="text/template" id="menuTemplate">
  <ul>
    {{for menu}}
      <li>
        {{i+1}}. <a href="{{v.url}}">{{v.caption}}</a>
      </li>
    {{/for}}
  </ul>
</script>
This call:
var func = _.template(document.getElementById('menuTemplate'))
func({
  menu: [
    {url: '//squizzle.me', caption: "Squizzle's home"},
    {url: '//squizzle.me/js/sqimitive', caption: "Sqimitive.js"},
  ],
}, {escaper: _.escape})
…will produce:
<ul>
  <li>
    1. <a href="//squizzle.me">Squizzle&39;s home</a>
  </li>
  <li>
    2. <a href="//squizzle.me/js/sqimitive">Sqimitive.js</a>
  </li>
</ul>
ExampleUsing prepare:
var f = _.template('{{a}}', {prepare: {a: '&', o: {escaper: _.escape}}})
f()                             //=> '&amp;'
f({a: '<'})                     //=> '&lt;'
f({}, {escaper: null})          //=> '&'
f({a: '<'}, {escaper: null})    //=> '<'
To force certain variables and/or options wrap the returned function:
var f = _.template('{{a}}')
var w = function (v, o) {
  _.assign({}, v, {a: '&'})
  _.assign({}, o, {escaper: _.escape})
  return f(v, o)
}
w({a: '<'}, {escaper: null})    //=> '&amp;'
Function form of prepare is useful if the template is compiled early but the defaults it should use change over time:
var f = _.template('{{r}}', {prepare: {r: Math.random(), o: {}}})
f()         //=> 0.2446989
f()         //=> 0.2446989
f({r: -1})  //=> -1

var f = _.template('{{r}}', {prepare: function (v, o) {
  return {r: Math.random(), o: o}
    // ignores all caller-given variables, keeps its options
  return _.assign({}, v, {r: Math.random(), o: o})
    // overrides r's value, keeps other variables and all options
}})
f()         //=> 0.0682551
f()         //=> 0.4187164
f({r: -1})  //=> 0.1058262
Example
var f = _.template(`
  {{for a}}
    a
  {{elseif b}}
    b
  {{else}}
    c
  {{/if}}
`)
// Equivalent to:
var f = _.template(`
  {{for a}}
    a
  {{/for}}
  {{if i == -1 && v.b}}
    b
  {{elseif i == -1}}
    c
  {{/if}}
`)

f()                 //=> 'c'
f({b: true})        //=> 1
f({a: [1, 2, 3]})   //=> 'aaa'
Exampleloop’s variables shadow global ones by the same name; globals are still accessible only with enabled options.with. In any case, use :pf to avoid shadowing.
{{v.x}}                         // x of the global object
{{for v.y}} {{v.x}} {{/for}}    // x of the member being looped over
{{for v.y}} {{x}} {{/for}}
  // if options.with is enabled, x is of the global object, else
  // it's an error (lexRef = false) or ''
{{for:f v.y}} {{v.x}} {{fv.x}} {{/for}}
ExampleCustom block:
var sample = function (param, value, c) {
  return {start: '_.sample(' + c.ref(value) + ')'}
}
_.template('{{sample items}}', {blocks: {sample}})
  ({items: ['a', 'b', 'c']})
    //=> 'a' or 'b' or 'c'

Defined in: nodash.js, lines 2370-2520 (151 lines) • Show code

template: function (str, options) {
  options = NoDash.assign({}, options, {with: null, laxRef: true,
                                        code: true, blocks: {}})

  options.blocks = NoDash.assign({
    if: function (param, value, c) {
      if (param == 'not') {
        param = '!'
      } else if (param) {
        throw new Error('template: bad "if:' + param + '".')
      }
      return {start: '(' + param + c.ref(value) + '?""', end: ':"")'}
    },
    elseif: function (param, value, c) {
      if ((c.stack[0] || {}).type == 'for') {
        param = (param === false ? '-' : param).match(/^(\w*|-)(:(.*))?$/)
        var ref = function (s) {
          return (param[1] == '-' ? c._lastFor : param[1]) + 'i==-1&&' + c.ref(s)
        }
        var res = object.blocks.if(param[3], value, {ref: ref})
        res.start = c.stack.shift().end + '+' + res.start
        res.type = 'if'
        return res
      } else if ((c.stack[0] || {}).type != 'if' || c.stack[0]._else) {
        throw new Error('template: elseif: no preceding if or for.')
      } else {
        var res = object.blocks.if.apply(this, arguments)
        c.stack[0].end = res.end + stack[0].end
        return {start: ':' + res.start}
      }
    },
    else: function (param, value, c) {
      if ((param && ((c.stack[0] || {}).type != 'for')) || value) {
        throw new Error('template: else takes no arguments.')
      } else {
        var ce = NoDash.assign({}, c, {ref: function () { return 1 }})
        return NoDash.assign(object.blocks.elseif(param, '', ce), {_else: true})
      }
    },
    for: function (pf, value, c) {
      if (!/^\w*$/.test(pf)) {
        throw new Error('template: bad "for:' + pf + '".')
      }
      c._lastFor = pf
      return {
        head: 'var ' + pf + 'i=-1;',
        start: '(' + pf + 'i=0,' +
               '_.map(' + c.ref(value) + ',' +
               'function(' + pf + 'v,' + pf + 'k,' + pf + 'vv){' +
               pf + 'i++;return"',
        end: '""}).join("")',
      }
    },
  }, options.blocks)

  var dotted = function (s, delim) {
    return '["' + s.replace(/\./g, '"' + delim + '"') + '"]'
  }

  var c = {
    options: options,
    stack: [],
    _lastFor: null,

    ref: function (s) {
      if (!s || !/\S/.test(s)) { throw new Error('template: blank ref.') }
      if (/^[\w.]+$/.test(s)) {
        s = options.laxRef
          ? '_.at(v, ' + dotted(s, ',') + ')' : 'v' + dotted(s, '][')
      } else if (!options.code) {
        throw new Error('template: code refs prohibited.')
      } else {
        haveCode = s = '(' + s + ')'
      }
      return s
    },
  }

  var haveCode = false
  var blocks = NoDash.keys(options.blocks).join('|')
  var blockStart  = new RegExp('^(' + blocks + ')(:\w*)?(\s+(.*))?$')
  var blockEnd    = new RegExp('^\\/\s*(' + blocks + ')?\s*$')

  if (str instanceof Function) {
    // RegExp /.../s flag is not supported in FF.
    str = NoDash.trim(str.toString().match(/\/\*([\s\S]*)\*\//)[1])
  } else if (NoDash.isElement(str)) {
    str = str.textContent
  }

  str =
    'return"' +
    str.replace(/(\\(\\\\)*)\{\{|(\\\\)*\{\{\s*(.*?)\}\}|(["\\])/g, function (m) {
      if (m[1]) {
        var res = m[0].substr(1)
      } else if (m[5]) {    // " or \.
        var res = '\\' + m[0]
      } else {
        var res = m[3] + '"+'
        var inside = m[4]
        if (inside[0] == '=') {
          res += '(' + c.ref(inside.substr(1)) + '||"")'
        } else if (m = inside.match(blockStart)) {
          var block = options.blocks[m[1]](m[2] ? m[2].substr(1) : false,
                                           m[3] ? m[4] : false, c)
          str += block.head || ''
          res += block.start || ''
          block.type = block.type || m[1]
          block.end && c.stack.unshift(block)
        } else if (m = inside.match(blockEnd)) {
          if (!c.stack.length || (m[1] && c.stack[0].type != m[1])) {
            var stack = c.stack.length ? '{{/' + c.stack[0].type + '}}' : 'no block'
            throw new Error('template: ' + m[0] + ' expected, ' + stack + ' found.')
          }
          res += c.stack.shift().end
        } else {
          res += '(o.escaper?o.escaper(' + c.ref(inside) + '||""):' +
                 c.ref(inside) + '||"")'
        }
        res += '+"'
      }
      return res
    }) +
    '"'

  if (c.stack.length) {
    var stack = NoDash.pick(c.stack, 'type').join('}} {{/')
    throw new Error('template: unclosed {{/' + stack + '}}.')
  }

  if (options.with == null ? haveCode : options.with) {
    str = 'with(v){' + str + '}'  // str may contain "var".
  }

  if (!options.defaults) {
    var prepare = function (v, o) { return v.o = o, v }
  } else if (typeof options.defaults != 'function') {
    var prepare = function (v, o) {
      return NoDash.assign({}, options.defaults, v,
                           {o: NoDash.assign({}, options.defaults.o, o)})
    }
  } else {
    var prepare = options.defaults
  }

  // It appears that strict mode isn't applied to such functions even
  // though it applies to eval, neither when they're created nor called.
  // But unlike eval such functions have access to the global scope only.
  return (new Function('p, _, v, o', 'v=p(v||{},o||{});o=v.o;' + str))
    .bind(undefined, prepare, NoDash)
},
throttle ( func, ms )

Returns a function that invokes func not moroe often than once per ms.

Arguments
Name Types Notes
func Subject to bind()
msint

See debounce().

ExampleIf ms is 100 and the function is called, then again called after 200 ms – func is only called once.

Defined in: nodash.js, lines 1738-1747 (10 lines) • Show code

throttle: function (func, ms) {
  func = bind(func)
  var last = 0
  return function () {
    if (Date.now() - last >= ms) {
      last = Date.now()
      func.apply(this, arguments)
    }
  }
},
times ( times, func, cx )

Calls func several times, returning results of all call.

Result Types
Types Notes
array
Arguments
Name Types Notes
timesint
func Subject to bind(); receives a number from 0 to times - 1

See also range().

Example
_.times(3, i => -i)   //=> [-0, -1, -2]

Defined in: nodash.js, lines 1880-1885 (6 lines) • Show code

times: function (times, func, cx) {
  func = bind(func, arguments, 2)
  return NoDash.fill(Array(times)).map(function (aNull, index) {
    return func.call(undefined, index)
  })
},
toArray ( value )

Converts value to a regular Array.

Result Types
Types Notes
array
Arguments
Name Types Notes
valuearray shallow-copied
object values returned
string returned as [value]
other array-like returned slice()’d
other errored

See also isArrayLike(), values().

Example
_.toArray('abc')                    //=> ['abc']
_.toArray(['a', 'b'])               //=> copy of the argument
_.toArray({a: 1, b: 2})             //=> [1, 2]
_.toArray({a: 1, b: 2, length: 0})  //=> []

Defined in: nodash.js, lines 1344-1355 (12 lines) • Show code

toArray: function (value) {
  if (!NoDash.isArrayLike(value)) {
    return Object.keys(value).map(function (key) {
      return value[key]
    })
  } else if (typeof value == 'string') {
    return [value]
  } else {
    // Array.prototype.concat.call(arguments) returns [arguments].
    return ap.slice.call(value)
  }
},
trim ( value [, blank] )

Returns a copy of value with certain “blanks” in start and end removed.

Result Types
Types Notes
trarray
object
string
Arguments
Name Types Notes
valuearray
object
string
blankmixed for array/object value
string
omitted = falsy for array/object, whitespace /\s/ for string

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

For object value this function sees arbitrary members as “start”/"end".

Example
_.trim(' abca ')            //=> 'abca'
_.trim('abca ', 'ba')       //=> 'ca '
_.trim('.ab.', '.*')        //=> 'ab' (blank is raw, not a RegExp)
_.trim(['ab', 'cd'], 'ab')  //=> ['cd']
_.trim(Array(5))            //=> []
_.trim({a: null, b: 1, c: false})   //=> {b: 1}

ECMAScript equivalent: o:String/trim. See also trimStart(), trimEnd().

Defined in: nodash.js, lines 928-930 (3 lines) • Show code

trim: function (value, blank) {
  return trim(true, true, value, blank, arguments.length < 2)
},
trimEnd ( value [, blank] )

Returns a copy of value with certain trailing “blanks” removed.

from tr

Result Types
Types Notes
array
object
string
Arguments
Name Types Notes
valuearray
object
string
blankmixed for array/object value
string
omitted = falsy for array/object, whitespace /\s/ for string

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

For object value this function sees arbitrary members as “start”/"end".

Example
_.trim(' abca ')            //=> 'abca'
_.trim('abca ', 'ba')       //=> 'ca '
_.trim('.ab.', '.*')        //=> 'ab' (blank is raw, not a RegExp)
_.trim(['ab', 'cd'], 'ab')  //=> ['cd']
_.trim(Array(5))            //=> []
_.trim({a: null, b: 1, c: false})   //=> {b: 1}

ECMAScript equivalent: o:String/trimEnd (not in IE). See also trim(), trimStart().

Defined in: nodash.js, lines 946-948 (3 lines) • Show code

trimEnd: function (value, blank) {
  return trim(false, true, value, blank, arguments.length < 2)
},
trimStart ( value [, blank] )

Returns a copy of value with certain leading “blanks” removed.

from tr

Result Types
Types Notes
array
object
string
Arguments
Name Types Notes
valuearray
object
string
blankmixed for array/object value
string
omitted = falsy for array/object, whitespace /\s/ for string

from unordered

Attention: be wary about object value – JavaScript objects are unordered.

For object value this function sees arbitrary members as “start”/"end".

Example
_.trim(' abca ')            //=> 'abca'
_.trim('abca ', 'ba')       //=> 'ca '
_.trim('.ab.', '.*')        //=> 'ab' (blank is raw, not a RegExp)
_.trim(['ab', 'cd'], 'ab')  //=> ['cd']
_.trim(Array(5))            //=> []
_.trim({a: null, b: 1, c: false})   //=> {b: 1}

ECMAScript equivalent: o:String/trimStart (not in IE). See also trim(), trimEnd().

Defined in: nodash.js, lines 937-939 (3 lines) • Show code

trimStart: function (value, blank) {
  return trim(true, false, value, blank, arguments.length < 2)
},
union ( ...values )

Returns a combination of members of all arguments without duplicates (unless they exist in the first argument).

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuesarray
object unlike with assign(), on duplicate key the first member’s value is kept

ECMAScript equivalent: o:Array/concat. See also assign(), intersection().

Example
_.union([1, 2], [1, 3])               //=> [1, 2, 3]
_.union({a: 1, b: 2}, {a: 3, c: 4})   //=> {a: 1, b: 2, c: 4}

…values

Defined in: nodash.js, lines 1434-1445 (12 lines) • Show code

union: function (/* ...values */) {
  var res = arguments[0] || []
  var isArray = NoDash.isArrayLike(res)
  for (var i = 1; i < arguments.length; i++) {
    NoDash.forEach(arguments[i], function (item, key) {
      if (!NoDash.includes(res, item)) {
        isArray ? res.push(item) : (res[key] = item)
      }
    })
  }
  return res
},
unique ( value [, func [, cx]] )

Returns a sorted copy of value without identical (===) members.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object first member’s value is kept
funcfunction ranking members of value as if by groupBy()
omitted to sort by member’s value
Example
_.unique([2, 1, 2])             //=> [1, 2]
_.unique([2, 1, 2], v => -v)    //=> [2, 1] (ranked as -2, -1)
_.unique({a: 1, b: 1})          //=> {a: 1}

Defined in: nodash.js, lines 1489-1502 (14 lines) • Show code

unique: function (value, func, cx) {
  var prev = unset
  if (arguments.length < 2) {
    return NoDash.filter(NoDash.sort(value), function (item) {
      return prev !== item
    })
  } else {
    var entries = tagAndSort(value, func, cx)
      .filter(function (item) { return prev !== item[2] })
    return NoDash.isArrayLike(value)
      ? entries.map(function (item) { return item[1] })
      : NoDash.fromEntries(entries)
  }
},
unzip ( value )

Splits members of value into multiple collections, each containing all members’ values for a particular property.

Result Types
Types Notes
array of arrays
object
Arguments
Name Types Notes
valuearrays of arrays
array of objects

See also zip() that does the reverse.

Example
_.unzip([])   //=> []

_.unzip([ ['a', 1, true], ['b', undefined, false], ['c', 3, undefined] ])
  //=> [ ['a', 'b', 'c'], [1, undefined, 3], ['c', 3, undefined] ]

_.unzip([ {a: 'a', b: 1, c: true}, {a: 'b', c: false}, {a: 'c', b: 3} ])
  //=> {a: ['a', 'b', 'c'], b: [1, undefined, 3], c: [true, false]})

Defined in: nodash.js, lines 1547-1557 (11 lines) • Show code

unzip: function (value) {
  if (NoDash.isArrayLike(args[0])) {
    var list = NoDash.max(value, function (item) { return item.length })
  } else {
    var list = value.length
      ? NoDash.assign.apply(undefined, [{}].concat(value)) : [[]]
  }
  return NoDash.map(list, function (item, key) {
    return NoDash.map(value, function (o) { return o[key] })
  })
},
values ( value )

Returns values of members in value.

Result Types
Types Notes
array with hasOwn() properties
Arguments
Name Types Notes
valuearray In all cases returns a shallow copy.
object

ECMAScript equivalent: o:Array/slice, o:Object/values. See also toArray(), keys().

Example
_.values([1, 2])        //=> [1, 2]
_.values(Array(3))      //=> [<3 empty slots>]
_.values({a: 1, b: 2})  //=> [1, 2]
_.values('abc')         //=> ['a', 'b', 'c']

Defined in: nodash.js, lines 725-732 (8 lines) • Show code

values: function (value) {
  // ap.slice() splits a string, ap.concat() doesn't.
  return transform(value, [], 0, ap.slice, function () {
    return Object.keys(value).map(function (key) {
      return value[key]
    })
  })
},
without ( value , ...members )

Returns a copy of values without members given as other arguments.

Result Types
Types Notes
array
object
Arguments
Name Types Notes
valuearray
object

See also difference().

Example
_.without([1, 2, 3], 2, 1)      //=> [3]
_.without({a: 1: b: 4}, 2, 1)   //=> {b: 4}

, …members

Defined in: nodash.js, lines 1417-1422 (6 lines) • Show code

without: function (value /* , ...members */) {
  var values = ap.slice.call(arguments, 1)
  return NoDash.filter(value, function (item) {
    return values.indexOf(item) == -1
  })
},
zip ( ...values )

Puts member of every argument into that argument’s position in the unified returned collection.

Result Types
Types Notes
array of arrays
array of objects (of duplicate keys last is used)
Arguments
Name Types Notes
valuesarrays of arrays
objects with array properties

See also unzip() that does the reverse.

Example
_.zip()   //=> []

_.zip(['a', 'b', 'c'], [1, undefined, 3], {0: true, 1: false})
  //=> [ ['a', 1, true], ['b', undefined, false], ['c', 3, undefined] ]

_.zip({a: ['a', 'b', 'c'], b: [1, undefined, 3]}, {c: {0: true, 1: false}})
  //=> [ {a: 'a', b: 1, c: true}, {a: 'b', b: undefined, c: false},
  //     {a: 'c', b: 3, c: undefined} ]

_.zip({a: [ignored...]}, {a: [1, 2, 3]})
// Same as:
_.zip(                   {a: [1, 2, 3]})

…values

Defined in: nodash.js, lines 1522-1532 (11 lines) • Show code

zip: function (/* ...values */) {
  var args = ap.slice.call(arguments)
  if (!NoDash.isArrayLike(args[0])) {
    args = args.length
      ? NoDash.assign.apply(undefined, [{}].concat(args)) : [[]]
  }
  return NoDash.max(args, function (a) { return a.length })
    .map(function (item, index) {
      return NoDash.map(args, function (a) { return a[index] })
    })
},