0.0.5 • Published 11 years ago
mu-unique v0.0.5
mu-unique
Uniqueify an array of elements.
Runtime complexity: O(n*log(n)) for sortable arrays, O(n^2) for
non-sortable arrays.
unique(arr, sortable, comparator)
arr {Array}- The source array.sortable {Boolean}- Optional. Does the array contain sortable elements? defaults tofalse.comparator {Function}- Optional.- If the array is sortable, it defines the order of the elements in the
array. It is called with 2 elements from the array and should return
0if they are equal, a positive number ifais bigger and a negative number ifbis bigger. If not provided, the array will be sorted with a natural order (as defined by the runtime). - If the array is not sortable, it defines the equality between elements
in the array. It is called with 2 elements from the array and should
return
trueif they are equal, andfalseotherwise. If not provided, the elements will be tested for equality with===.
- If the array is sortable, it defines the order of the elements in the
array. It is called with 2 elements from the array and should return
Notes:
- The function modifies the array and returns its new length.
- The original order of items may not be preserved.
- If the
thisvalue of the function is defined, it will be used as the array (see examples). Thus it is possible to use this function to extend the Array prototype:Array.prototype.unique = unique.
Installation
- Node:
npm install mu-uniquevar unique = require('mu-unique');
- AMD (install with bower):
bower install mu-uniquerequire(['mu-unique'], function(unique){ /* ... */ });
Run tests with make test.
Run coverage analysis with make coverage (coverage report is saved to ./coverage).
Examples
var arr = [1, 2, 1, 2, 3],
len = unique(arr);
console.log(arr, true); // [1, 2, 3]
console.log(len); // 3var o1 = {},
o2 = function(){},
o3 = "foo",
arr = [o1,o1,o2,o3,o2,o3],
len = unique(arr);
console.log(arr); // [o1, o2, o3]
console.log(len); // 3With a custom order:
var arr1 = ['hello', 'hi', 'world'],
arr2 = unique(arr1, function(a, b){
// compare only first character
return a[0] > b[0] ? 1 : a[0] < b[0] ? -1 : 0;
});
console.log(arr1); // ['hello', 'hi', 'world']
console.log(arr2); // ['hello', 'world']By setting the this value:
var arr = [1, 2, 1, 2, 3],
len = unique.call(arr);
console.log(arr); // [1, 2, 3]
console.log(len); // 3