@aliretail/react-materials-components
Version:
92 lines (74 loc) • 2.46 kB
JavaScript
/**
* 合并地区
* 由于逐级异步加载地区会导致非一级地区在二次打开时上级地区无法被识别,选择上级地区时会出现上级地区和下级tag同时存在
* @param codes 由地区行政编码组成的数组列表
* @return 合并后的地区行政编码的数组列表
*/
export var mergeRegionCodes = function mergeRegionCodes(codes) {
if (codes === void 0) {
codes = [];
}
var isProvince = function isProvince(code) {
// 地址码是六位,而且只有省级位有值
return code.toString().length === 6 && code % 10000 === 0;
};
var isCity = function isCity(code) {
// 地址码是六位,而且只有省级位和市级位有值
return code.toString().length === 6 && code % 100 === 0;
};
/**
* 判断两个code之间的关系:-1 -- a是b的祖先,0 -- a和b没有层级关系,1 -- b是a的祖先
* @param a
* @param b
* @returns
*/
var calculateRelationship = function calculateRelationship(a, b) {
if (a === b) {
return -1;
}
if (isProvince(a) || isProvince(b)) {
if (b.toString().substr(0, 2) === a.toString().substr(0, 2)) {
return isProvince(a) ? -1 : 1;
}
return 0;
}
if (isCity(a) || isCity(b)) {
if (b.toString().substr(0, 4) === a.toString().substr(0, 4)) {
return isCity(a) ? -1 : 1;
}
return 0;
}
if (a.toString().length !== b.toString().length) {
if (b.toString().substr(0, 6) === a.toString().substr(0, 6)) {
return a.toString().length === 6 ? -1 : 1;
}
return 0;
}
return 0;
};
var result = [];
codes.forEach(function (code) {
var ret = 0;
if (result.length > 0) {
var needToPopCodes = [];
result.forEach(function (rCode) {
var rRet = calculateRelationship(rCode, code); // 如果两个之间有层级关系,需要明确去留
if (rRet !== 0) {
ret = rRet; // 如果新的code是原来的祖先,需要把新的加进来,同时踢掉旧的
if (rRet === 1) {
needToPopCodes.push(rCode);
}
}
});
if (needToPopCodes.length > 0) {
result = result.filter(function (rCode) {
return needToPopCodes.indexOf(rCode) === -1;
});
}
} // 如果新的不是已有的code里面的子孙,就加进去
if (ret !== -1) {
result.push(code);
}
});
return result;
};