zoukankan      html  css  js  c++  java
  • [源计划] array-uniq

    array-uniq

    数组去重

    来源

    示例

    const arrayUniq = require('array-uniq');
    
    arrayUniq([1, 1, 2, 3, 3]);
    //=> [1, 2, 3]
    
    arrayUniq(['foo', 'foo', 'bar', 'foo']);
    //=> ['foo', 'bar']
    

    源码

    'use strict';
    
    // there's 3 implementations written in increasing order of efficiency
    
    // 1 - no Set type is defined
    function uniqNoSet(arr) {
    	var ret = [];
    
    	for (var i = 0; i < arr.length; i++) {
    		if (ret.indexOf(arr[i]) === -1) {
    			ret.push(arr[i]);
    		}
    	}
    
    	return ret;
    }
    
    // 2 - a simple Set type is defined
    function uniqSet(arr) {
    	var seen = new Set();
    	return arr.filter(function (el) {
    		if (!seen.has(el)) {
    			seen.add(el);
    			return true;
    		}
    
    		return false;
    	});
    }
    
    // 3 - a standard Set type is defined and it has a forEach method
    function uniqSetWithForEach(arr) {
    	var ret = [];
    
    	(new Set(arr)).forEach(function (el) {
    		ret.push(el);
    	});
    
    	return ret;
    }
    
    // V8 currently has a broken implementation
    // https://github.com/joyent/node/issues/8449
    function doesForEachActuallyWork() {
    	var ret = false;
    
    	(new Set([true])).forEach(function (el) {
    		ret = el;
    	});
    
    	return ret === true;
    }
    
    if ('Set' in global) {
    	if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) {
    		module.exports = uniqSetWithForEach;
    	} else {
    		module.exports = uniqSet;
    	}
    } else {
    	module.exports = uniqNoSet;
    }
    
    
  • 相关阅读:
    excel合并单元格
    layer单元格合并
    跨域打开页面:Uncaught DOMException: Blocked a frame with origin
    nginx配置ws
    123
    java集合框架初探-迭代器
    java集合框架初探
    123123
    java switch
    java-测试开始map基本操作
  • 原文地址:https://www.cnblogs.com/aaronzhou001/p/10286122.html
Copyright © 2011-2022 走看看