Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function uniquePrimitives(array){
- var hash = Object.create(null),
- out = [],
- i = array.length;
- while (i--) {
- if (!hash[array[i]]) {
- hash[array[i]] = true;
- out.push(array[i]);
- }
- }
- return out;
- }
- var unique = function(){
- var hasOwn = {}.hasOwnProperty,
- uids = {};
- function uid(){
- var str = '_' + Math.random().toString(36);
- if (str in uids)
- return uid();
- uids[str] = true;
- return str;
- }
- function unique(array){
- var strings = {}, numbers = {}, others = {},
- tagged = [], failed = [],
- count = 0, i = array.length,
- item, type;
- var id = uid();
- while (i--) {
- item = array[i];
- type = typeof item;
- if (item == null || type !== 'object' && type !== 'function') {
- // primitive
- switch (type) {
- case 'string': strings[item] = true; break;
- case 'number':
- if (1 / item === -Infinity)
- // negative zero
- others[item] = item;
- else
- numbers[item] = true;
- break;
- default: others[item] = item; break;
- }
- } else {
- // object
- if (!hasOwn.call(item, id)) {
- try {
- // set key ON each object tagging it as "seen"
- item[id] = true;
- tagged[count++] = item;
- } catch (e){
- if (failed.indexOf(item) === -1)
- failed[failed.length] = item;
- }
- }
- }
- }
- // remove the tags
- while (count--)
- delete tagged[count][id];
- tagged = tagged.concat(failed);
- count = tagged.length;
- // append primitives to results
- for (i in strings)
- if (hasOwn.call(strings, i))
- tagged[count++] = i;
- for (i in numbers)
- if (hasOwn.call(numbers, i))
- tagged[count++] = +i;
- for (i in others)
- if (hasOwn.call(others, i))
- tagged[count++] = others[i];
- return tagged;
- }
- return unique;
- }();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement