Skip to content

Commit

Permalink
Merge pull request #142 from golyshevd/fix-sort-obj
Browse files Browse the repository at this point in the history
Fix _sortObj
  • Loading branch information
eGavr authored Aug 8, 2016
2 parents 5cd1af9 + a504cff commit 6d56b25
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 13 deletions.
29 changes: 16 additions & 13 deletions lib/utils/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,20 +80,23 @@ function sortAttrsValues(attrs, compareAttributesAsJSON) {
* @returns {Object}
*/
function _sortObj(obj) {
var keys = _.keys(obj).sort(),
sortedObj = {};

_.forEach(keys, function (key) {
var objValue = obj[key];

if (_.isPlainObject(objValue)) {
objValue = _sortObj(objValue);
}
if (!_.isObject(obj)) {
return JSON.stringify(obj);
}

sortedObj[key] = objValue;
});
if (_.isArray(obj)) {
return '[' + _(obj).map(_sortObj).join(',') + ']';
}

return sortedObj;
return '{' +
_(obj)
.keys()
.sort()
.map(function (key) {
return JSON.stringify(key) + ':' + _sortObj(obj[key]);
})
.join(',') +
'}';
}

/**
Expand Down Expand Up @@ -132,7 +135,7 @@ function sortAttrsValues(attrs, compareAttributesAsJSON) {
_.forEach(attrIndexes, function (index) {
attrValue = _parseAttr(attrs[index].value, isFunction);

attrValue && (attrValue = JSON.stringify(_sortObj(attrValue)));
attrValue = _sortObj(attrValue);

attrs[index].value = (isFunction && attrValue ? 'return ' : '') + attrValue;
});
Expand Down
17 changes: 17 additions & 0 deletions test/unit/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,23 @@ describe('\'utils\'', function () {
utils.sortAttrsValues(input, options).must.be.eql(output);
});

it('must correctly sort attributes\' values which are objects inside arrays', function () {
var options = [
'a',
{ name: 'onclick', isFunction: true }
],
input = [
{ name: 'a', value: '{"a":[{"b":"b","a":"a"}]}' },
{ name: 'onclick', value: 'return {"a":[{"b":"b","a":"a"}]}' }
],
output = [
{ name: 'a', value: '{"a":[{"a":"a","b":"b"}]}' },
{ name: 'onclick', value: 'return {"a":[{"a":"a","b":"b"}]}' }
];

utils.sortAttrsValues(input, options).must.be.eql(output);
});

it('must remove attributes\' values', function () {
var input = [
{ name: 'a', value: 'a' },
Expand Down

0 comments on commit 6d56b25

Please sign in to comment.