forked from helpers/handlebars-helpers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollection.js
86 lines (75 loc) · 1.82 KB
/
collection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
var array = require('./array');
var object = require('./object');
var utils = require('./utils');
var forEach = array.forEach;
var forOwn = object.forOwn;
/**
* Expose `helpers`
*/
var helpers = module.exports;
/**
* Block helper that returns a block if the given collection is
* empty. If the collection is not empty the inverse block is returned
* (if supplied).
*
* @name .isEmpty
* @param {Object} `collection`
* @param {Object} `options`
* @return {String}
* @block
* @api public
*/
helpers.isEmpty = function(collection, options) {
if (options == null) {
options = collection;
return options.fn(this);
}
if (Array.isArray(collection) && !collection.length) {
return options.fn(this);
}
var keys = Object.keys(collection);
if (typeof collection === 'object' && !keys.length) {
return options.fn(this);
}
return options.inverse(this);
};
/**
* Iterate over an array or object,
*
* @name .iterate
* @param {Object|Array} `context` The collection to iterate over
* @param {Object} `options`
* @return {String}
* @block
* @api public
*/
helpers.iterate = function(context, options) {
if (Array.isArray(context)) {
return forEach.apply(forEach, arguments);
} else if (utils.isObject(context)) {
return forOwn.apply(forOwn, arguments);
}
return options.inverse(this);
};
/**
* Returns the length of the given collection.
*
* ```handlebars
* {{length "['a', 'b', 'c']"}}
* //=> 3
* ```
* @param {Array|Object|String} `value`
* @return {Number} The length of the value.
* @api public
*/
helpers.length = function(value) {
if (utils.isUndefined(value)) return '';
if (typeof value === 'string' && /[[]/.test(value)) {
value = utils.tryParse(value) || [];
}
if (utils.isObject(value)) {
value = Object.keys(value);
}
return value.length;
};