array-more
Version:
Expanding More Methods on Array Prototype Objects
117 lines (111 loc) • 3.53 kB
JavaScript
String = require('drin-string');
/**
* 返回数组内部元素的数据类型
* @return { string[] }
*/
Array.prototype.types = function() {
return this.map(item => {
// 返回数据类型
return Object.prototype.toString.call(item).replace(/^\[object\s(.+?)\]$/,'$1');
});
}
/**
* 统计数组中某个元素的个数
* @param { any } value
* @return {number}
*/
Array.prototype.count = function(value) {
if( !this.includes(value) ) return 0;
let total = 0,that = this.slice(0);
while(that.length) {
let last = that.pop();
if(last === value) total++;
}
return total;
}
/**
* 判断数组内部元素是否具有相同的数据类型
* @param { string } type 类型名称
* @return { boolean }
*/
Array.prototype.isSameType = function(type) {
const types = this.types();
return types.count(type ? type.ucfirst() : types[0]) === types.length;
}
/**
* 去除数组中重复的值
* @return { *[] }
*/
Array.prototype.unique = function() {
let data = [];
for(let i = 0;i<this.length;i++) {
if(data.indexOf(this[i]) === -1) {
data.push(this[i]);
}
}
return data;
}
/**
* 按条件查询数组
* @param { string } condition 查询条件
* @param { any } value
* @return {*[]}
*/
Array.prototype.query = function(condition='',value) {
let find = [];
if( /[A-Z]/.test(condition) ) condition = condition.lower();
for(let i = 0;i<this.length;i++) {
switch (condition) {
case '>':
if(this[i] > value) find.push(this[i]);
break;
case '<':
if(this[i] < value) find.push(this[i]);
break;
case '>=':
if(this[i] >= value) find.push(this[i]);
break;
case '<=':
if(this[i] <= value) find.push(this[i]);
break;
case '==':
if(this[i] == value) find.push(this[i]);
break;
case '!=':
if(this[i] != value) find.push(this[i]);
break;
case '===':
if(this[i] === value) find.push(this[i]);
break;
case '!==':
if(this[i] !== value) find.push(this[i]);
break;
case 'like':
if( /\*/.test(value) ) {
const rule = new RegExp('^'+value.escapeRegExp().replaceAll('\\*','[^]+') +'$');
if( rule.test(this[i]) ) find.push(this[i]);
} else if(/_/.test(value)) {
const rule = new RegExp('^'+value.escapeRegExp().replaceAll('_','[^]') +'$');
if( rule.test(this[i]) ) find.push(this[i]);
} else {
if(this[i] === value) find.push(this[i]);
}
}
}
return find;
}
/**
* 返回或校验数组的具体类型
* @param { string } type
* @return { string }
*/
Array.prototype.typeof = function(type) {
const types = this.types();
const dataType = types.count(types[0]) === types.length ? types[0]+'[]' : '['+types.join()+']';
if(!type) return dataType;
if( /^\[.+\]$/.test(type) ) {
type = type.trim('[,]').split(',').map(t => t.ucfirst()).join().wrap('[,]');
}
return dataType === type.ucfirst();
}
module.exports = Array;