Skip to content

Instantly share code, notes, and snippets.

@hl4
Created July 15, 2018 13:18
Show Gist options
  • Save hl4/c190c98406b25ca8cf636c0b22806dc4 to your computer and use it in GitHub Desktop.
Save hl4/c190c98406b25ca8cf636c0b22806dc4 to your computer and use it in GitHub Desktop.
前缀序号生成算法
/**
* { id:标识符,
* pid: 父结点标识符
* prefix: 前缀, pid=0时前缀固定
* createTime: 创建或个性时间,当父节点相同时,时间小的排前面
* parent:通过initParent后计算出指向父节点对象(id==this.pid)
* }
*/
/** 生成父节点
*/
function initParent(coll) {
let map = new Map()
map.set(0, null)
for (let x of coll) {
map.set(x.id, x)
}
for (let x of coll) {
x.parent = map.get(x.pid)
}
}
/**排序函数
* 调用 data.sort(orderByRank) 排序
*/
function orderByRank(a, b) {
if (a.pid === b.pid) {
return a.createTime - b.createTime;
}
if (a.pid === 0 || b.pid === 0) {
return a.pid - b.pid;
}
return orderByRank(a.parent, b.parent)
}
/** 生成子节点的前缀
*/
function generatePrefix(coll) {
let number = 1, pid = "", prefix = ""
for (let x of coll) {
if (x.pid === 0) continue
if (x.parent.prefix != pid ) {
number = 1
pid = x.parent.prefix
prefix = x.parent.pid == 0 ? pid: pid + "."
}
x.prefix = prefix + number
number++
}
}
const topLevel = {
"F":0, "C":1, "D":2, "P":3
}
/** 按树形排序
* 调用方式 data.sort(orderByTree)
* 会用到的一个topLevel的首字母顺序表
*/
function orderByTree(a,b) {
if (a.prefix.charAt(0) === b.prefix.charAt(0)) return a.prefix.localeCompare(b.prefix)
return topLevel[a.prefix.slice(0,1)] - topLevel[b.prefix.slice(0,1)]
}
/* 示例 */
let data = [
{ id:1, name : "financial", prefix : "F", pid:0, createTime:0},
{ id:2, name : "customer", prefix : "C", pid:0, createTime:1},
{ id:3, name : "development", prefix : "D", pid:0, createTime:2},
{ id:4, name : "process", prefix : "P", pid:0, createTime:3},
{ id:5, name : "financial.1", prefix : "", pid:1, createTime:1001},
{ id:6, name : "customer.1", prefix : "", pid:2, createTime:1002},
{ id:7, name : "financial.2", prefix : "", pid:1, createTime:1003},
{ id:8, name : "financial.1.1", prefix : "", pid:5, createTime:1001},
{ id:9, name : "customer.1.1", prefix : "", pid:6, createTime:1002},
{ id:10, name : "financial.1.2", prefix : "", pid:5, createTime:1003}
]
initParent(data)
data.sort(orderByRank)
generatePrefix(data)
data.sort(orderByTree)
for (let x of data) {
console.log(x.prefix + " " + x.name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment