Skip to content

Commit

Permalink
Merge pull request #9 from flowxo/add/limit-flatten
Browse files Browse the repository at this point in the history
Add limit option to getFlattenedFields
  • Loading branch information
shepherdsam authored Feb 28, 2017
2 parents 804db8e + 5f28e75 commit 91eaf76
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,9 @@ Utils.getFlattenedFields = function(data, options) {
options = options || {};
options.delimiter = options.delimiter || DEFAULT_FLATTENED_DELIMITER;
options.arrayDelimiter = options.arrayDelimiter || DEFAULT_FLATTENED_ARRAY_DELIMITER;
options.limit = options.limit || Infinity;

var output, addOutput;
var output, addOutput, outputCount = 0;

if(options.idx) {
// Return a hashmap.
Expand All @@ -288,6 +289,10 @@ Utils.getFlattenedFields = function(data, options) {
var flatten = function(o, prevKey, prevLabel, isCollection) {
var itr = _.isArray(o) ? _.forEach : _.forOwn;
itr(o, function(val, key) {
if (outputCount >= options.limit) {
return false;
}

// Nest the key
var delimiter = isCollection ? options.arrayDelimiter : options.delimiter;
var newKey = prevKey ? prevKey + delimiter + key : key;
Expand Down Expand Up @@ -317,6 +322,7 @@ Utils.getFlattenedFields = function(data, options) {
label: humanize(newLabel),
value: val
});
++outputCount;

});
};
Expand Down
41 changes: 41 additions & 0 deletions spec/specs.js
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,47 @@ describe('Utils', function() {
}]);
});

it('should return flattened fields and honor the limit option', function() {
var data = {
some: [
{key: 'value'},
{key: 'value'},
{key: 'value'},
{key: 'value'},
{key: 'value'},
{key: 'value'},
{key: 'value'},
{key: 'value'},
{key: 'value'},
{key: 'value'},
{key: 'value'}
]
};

var actual = Utils.getFlattenedFields(data, {limit: 5});
expect(actual).toEqual([{
key: 'some_+_key',
label: 'Some key',
value: undefined
}, {
key: 'some__0__key',
label: 'Some 0 key',
value: 'value'
}, {
key: 'some__1__key',
label: 'Some 1 key',
value: 'value'
}, {
key: 'some__2__key',
label: 'Some 2 key',
value: 'value'
}, {
key: 'some__3__key',
label: 'Some 3 key',
value: 'value'
}]);
});

it('should return flattened fields for an object with a custom delimiter', function() {
var data = {
some: {
Expand Down

0 comments on commit 91eaf76

Please sign in to comment.