qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

Day393:请实现 find 函数,使下列的代码调用正确.(蚂蚁金服) #396

Open qappleh opened 3 years ago

qappleh commented 3 years ago
// 约定:
// title数据类型为String
// userId为主键,数据类型为Number
var data = [
  {userId: 8,  title: 'title1'},
  {userId: 11, title: 'other'},
  {userId: 15, title: null},
  {userId: 19, title: 'title2'}
];
var find = function(origin) {
  // your code are here...
}
// 查找 data 中,符合条件的数据,并进行排序
var result = find(data).where({
  'title': /\d$/
}).orderBy('userId', 'desc');

console.log(result);// [{ userId: 19, title: 'title2'}, { userId: 8, title: 'title1' }]; 
zhuanghongbin commented 2 years ago
function find (origin) {
  return {
    where: function (obj) {
      let r = []
      r = origin.filter(item => {
        return item.title !== null && item.title.toString().search(obj.title) > -1
      })
      return {
        orderBy: function (field, orderTyep = 'desc') {
          let oo = {}
          r.map(o => {
            oo[o[field]] = o
          })
          let result = []
          Object.keys(oo).sort((a, b) => orderTyep === 'desc' ? b - a : a - b).forEach(i => { result.push(oo[i]) })
          return result
        }
      }
    }
  }
}
AliasT commented 2 years ago
function find(array) {
  return new S(data);
}

function S(data) {
  this.data = data;
  this.filters = {};
  this.orderings = [];
}

S.prototype.where = function (query) {
  this.filters = Object.assign(
    {},
    this.filters,
    Object.keys(query).reduce(
      // 这里要处理null等特殊值
      (a, c) => ((a[c] = (d) => query[c].test(d[c])), a),
      {}
    )
  );
  return this;
};

S.prototype.orderBy = function (field, desc = "desc") {
  this.orderings.push((a, z) =>
    desc == "desc" ? z[field] - a[field] : a[field] - z[field]
  );

  this.data = this.data.filter((d) =>
    Object.keys(this.filters).every((key) => this.filters[key](d))
  );

  this.orderings.forEach((o) => {
    this.data = this.data.sort(o);
  });

  return this.data;
};
ch3cknull commented 2 years ago
function find(array) {
  let data = [...array]

  data.__proto__.where = (obj) => {
    if (data.length == 0) return []
    Object.keys(obj).forEach((key) => {
      // 写法不太优雅,待完善
      if (!data[0].hasOwnProperty(key)) {
        data = []
      } else {
        data = data.filter((s) => obj[key].test(s[key]))
      }
    })
    return data
  }

  data.__proto__.orderBy = (key, sortMode) => {
    if (data.length == 0 || !data[0].hasOwnProperty(key)) return []
    return data.sort((x, y) => {
      return sortMode != 'desc' ? x[key] - y[key] : y[key] - x[key]
    })
  }

  return data
}

同时支持了

find(args)
  .where()
  .where()
  .orderBy()