Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

一道面试题的链式调用思考?

请实现find函数,使下列的代码调用正确。

约定:

  • title数据类型为string|null
  • id为主键,数据类型为number
var data = [
    {id: 1, title: 'title1'},
    {id: 2, title: 'other'},
    {id: 3, title: null},
    {id: 4, title: 'title2'}
];

var find = function(origin) {
    //your code are here...
}

//查找data中,符合条件的数据,并进行排序
var result = find(data).where({
    "title": /d$/
}).orderBy('id', 'desc');

console.log(result); // [{ id: 4, title: 'title2'}, { id: 2, title: 'other' },{id: 1, title: 'title1'}];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

有点类似orm里的查询了,以下是我简单写的一个:

class Query {
    constructor (dataList) {
        this.dataList = dataList
    }

    where (conditions) {
        const keyList = Object.keys(conditions)
        const dataList = this.dataList.filter(data => {
            return keyList.every(k => conditions[k].test(data[k]))
        })
        return new Query(dataList)
    }

    orderBy(key, orderType) {
        const func = (a, b) => (a[key] - b[key]) * (orderType == 'desc' ? -1 : 1)
        const list = [...this.dataList].sort(func)
        return new Query(list)
    }
}

function find (dataList) {
    return new Query(dataList)
}

var data = [
    {id: 1, title: 'title1'},
    {id: 2, title: 'other'},
    {id: 3, title: null},
    {id: 4, title: 'title2'}
]

let result = find(data).where({ title: /d$/ }).orderBy('id', 'desc')
console.log(JSON.stringify(result, null, 2))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...