Skip to content

Commit 313150e

Browse files
committed
add fill unique lib function,
- useful to fill fullLayout._modules and fullLayout._basePlotModules
1 parent 1c41c2e commit 313150e

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

src/lib/index.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,23 @@ lib.noneOrAll = function(containerIn, containerOut, attrList) {
335335
}
336336
};
337337

338+
/**
339+
* Fill with unique items
340+
*
341+
* @param {array} array
342+
* array to be filled
343+
* @param {any} item
344+
* item to be or not to be inserted
345+
* @return {array}
346+
* ref to array (now possibly containing one more item)
347+
*
348+
*/
349+
lib.fillUnique = function(array, item) {
350+
if(item && array.indexOf(item) === -1) array.push(item);
351+
352+
return array;
353+
};
354+
338355
lib.mergeArray = function(traceAttr, cd, cdAttr) {
339356
if(Array.isArray(traceAttr)) {
340357
var imax = Math.min(traceAttr.length, cd.length);

test/jasmine/tests/lib_test.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -770,4 +770,44 @@ describe('Test lib.js:', function() {
770770
});
771771
});
772772

773+
describe('fillUnique', function() {
774+
775+
beforeEach(function() {
776+
this.obj = { a: 'A' };
777+
this.array = ['a', 'b', 'c', this.obj];
778+
});
779+
780+
it('should fill new items in array', function() {
781+
var out = Lib.fillUnique(this.array, 'd');
782+
783+
expect(this.array).toEqual(['a', 'b', 'c', { a: 'A' }, 'd']);
784+
expect(this.array).toBe(out);
785+
});
786+
787+
it('should ignore falsy items', function() {
788+
Lib.fillUnique(this.array, false);
789+
expect(this.array).toEqual(['a', 'b', 'c', { a: 'A' }]);
790+
791+
Lib.fillUnique(this.array, undefined);
792+
expect(this.array).toEqual(['a', 'b', 'c', { a: 'A' }]);
793+
794+
Lib.fillUnique(this.array, 0);
795+
expect(this.array).toEqual(['a', 'b', 'c', { a: 'A' }]);
796+
797+
Lib.fillUnique(this.array, null);
798+
expect(this.array).toEqual(['a', 'b', 'c', { a: 'A' }]);
799+
800+
Lib.fillUnique(this.array, '');
801+
expect(this.array).toEqual(['a', 'b', 'c', { a: 'A' }]);
802+
});
803+
804+
it('should ignore item already in array', function() {
805+
Lib.fillUnique(this.array, 'a');
806+
expect(this.array).toEqual(['a', 'b', 'c', { a: 'A' }]);
807+
808+
Lib.fillUnique(this.array, this.obj);
809+
expect(this.array).toEqual(['a', 'b', 'c', { a: 'A' }]);
810+
});
811+
});
812+
773813
});

0 commit comments

Comments
 (0)