Add strict flag to sortObjectsByIds

When true, any object not in the ids will be discarded and a subset
will be returned.
This commit is contained in:
Fabien Franzen 2014-08-15 19:47:12 +02:00
parent 2c40319585
commit 3e300c1f35
2 changed files with 10 additions and 3 deletions

View File

@ -208,7 +208,7 @@ function isPlainObject(obj) {
function sortObjectsByIds(idName, ids, objects) {
function sortObjectsByIds(idName, ids, objects, strict) {
ids = ids.map(function(id) {
return (typeof id === 'object') ? id.toString() : id;
});
@ -225,6 +225,7 @@ function sortObjectsByIds(idName, ids, objects) {
objects.forEach(function(x) {
if (typeof x === 'object') {
var idx = indexOf(x);
if (strict && idx === -1) return;
idx === -1 ? tailing.push(x) : heading.push(x);
}
});

View File

@ -206,9 +206,15 @@ describe('sortObjectsByIds', function () {
});
it('should sort - partial ids', function() {
var sorted =sortObjectsByIds('id', [5, 3, 2], items);
var sorted = sortObjectsByIds('id', [5, 3, 2], items);
var names = sorted.map(function(u) { return u.name; });
should.deepEqual(names, ['e', 'c', 'b', 'a', 'd', 'f']);
});
it('should sort - strict', function() {
var sorted = sortObjectsByIds('id', [5, 3, 2], items, true);
var names = sorted.map(function(u) { return u.name; });
should.deepEqual(names, ['e', 'c', 'b']);
});
});