2
头图

Preface

As a crucial course in computer science, data structure and algorithm are often difficult to use or practice related in daily business code. The exercises we often practice in Leetcode feel useless. In fact, by optimizing some of the code on the page and in the process of requirement realization, we can draw inferences about the source code we have read before or the exercises we have practiced before by analogy. This article enumerates some relevant data structure algorithm practices and thoughts on algorithms and data structure exercises carried out by the author in the process of daily business code writing.

Business needs

  • Display of custom priority rules
  • Switch time granularity field mapping

Explore the plan

Display of custom priority rules

In the front-end page, we often encounter the need for a row of display numbers or different dimensional attributes. Generally speaking, we will display all the fields returned from the back-end, but in some scenes where light interaction and heavy display are used For example, a large visual screen requires us to make a decision on the displayed content, and this trade-off requires us to select and arrange the priority according to the demand or the feedback of the product data, and the dynamic adjustment process of the priority will be involved here. , That is, the display priority can be customized according to data or needs.

Option 1: Functional programming

图片

The first simpler idea is to split the array according to product requirements, and then merge the arrays for interception display

fn(arr) {
  let r = [], _r = [];
  for(let i=0; i < arr.length; i++) {
    // 数量展示优化
    if( 达到某个数量 ) return r;
    if(// 根据产品需求对数组进行分流) {
      r.push(arr[i])
    } else {
      _r.push(arr[i])
    }
  }

  return r.length > 5 ? r.slice(0,5) : r.concat(_r).slice(0,5);
};

gn() {
  this.resourceConfig.map(// 业务逻辑).sort((a,b) => a.structure - b.structure));
}

最后 fn(gn())

Option 2: Linked List

图片

The second solution comes from the convenient feature of deleting and updating the linked list. All the priorities are connected in series through a linked list, and the related business update operations are performed by using the update operation.

// 构造一个节点
class Node {
  constructor(v, next){
    this.value = v;
    this.next = next;
  }
}
 
class LinkList {
  constructor(){
    // 链表的属性,长度和头部
    this.size = 0
    this.head = new Node(null, null)
  }
    
  // 是否为空
  isEmpty() {
    return this.size === 0
  }
  
  // 更新链表,进行相关业务的操作
  update() {

  }
}

Option 3: Priority queue

图片

This solution is derived from the priority scheduling of react's fiber, and related operations are performed through the priority queue

class PriorityQueue{
    // 取父节点索引 ~~((index - 1) / 2)
    constructor(arr){
        if (arr.length){
            this.tree = []
            this._build_tree(arr);
            return;
        }
        this.tree = [];
    }

    // 入队
    enqueue(val){
        this.tree.push(val);
        // 上浮
        this._up(this.tree.length - 1);
    }

    // 出队
    dequeue(){
        // 取树根元素
        this.tree.shift();
        // 最后一个元素放树根,进行下沉
        let last = this.tree.pop();
        this.tree.unshift(last);
        // log(n)下沉
        this._down(0);
    }

    // 取队首的值
    getFirst(){
        return this.tree[0];
    }

    _build_tree(arr){
        let tree = this.tree;
        tree.push(arr[0]);
        for (let i = 1; i < arr.length; i++){
            tree.unshift(arr[i]);
            this._down(0);
        }
    }

    // 对index号元素执行下沉操作. 也叫heapify
    _down(index){
        let tree = this.tree;
        // 本身就是叶子节点,无需下沉
        let last_no_leaf = ~~((tree.length - 2) / 2);
        if (index > last_no_leaf) return;
        while(index <= last_no_leaf){
            let l = tree[index * 2 + 1];
            let r = tree[index * 2 + 2] || tree[index * 2 + 1]; // 有可能没有右儿子
            let max = l >= r ? l : r;
            let maxIndex = l >= r ? index * 2 + 1: index * 2 + 2
            if (tree[index] < max){
                [tree[index], tree[maxIndex]] = [tree[maxIndex], tree[index]]
                index = index * 2 + 1
            }else{
                return;
            }
        }
    }

    // 对index号元素执行上浮操作
    _up(index){
        let tree = this.tree;
        while(index !== 0){
            let p = ~~((index - 1) / 2);
            if (tree[index] > tree[p]){
                [tree[index], tree[p]] = [tree[p], tree[index]];
                // let tmp = index;
                // this._down(tmp);
                index = p;
            } else {
                return;
            }
        }
    }
}

Switch time granularity field mapping

In the front-end page, for the dynamic drop-down selection box option, we usually get it through the interface, but for the multi-level linkage drop-down selection option, for different time granular selections, the data name usually returned is the same but the id is indeed different. At this time, usually Need to map data

Scenario: Stack

图片

When the time granularity is switched, it is necessary to record the values of the two time granularities before and after the final one. The time granularity data mapping is performed through the interface. Here, the time granularity record can be performed through the stack to obtain the initial and final time granularity, and finally the data mapping is performed.

const timeSizeList = [];

// 进行入栈操作
timeSizeList.push(...)

to sum up

In the process of daily data structure exercises or reading the source code, in addition to coping with the interview, the most important thing is to learn the ideas and ideas for solving problems in the source code or exercises. In the daily business code, although it is difficult to write the framework code The kind of elegant and concise implementation scheme, but you should also think about how to use data structures and algorithms to optimize the time and space complexity of the code in your daily work, better optimize the execution of the code, and improve the user experience. This is a senior engineer. The details that should be paid attention to are not to complete the business code just to complete the business code. Although a lot of code has been written, in fact, the improvement of personal code ability and computer literacy is very limited. In the process of repetitive business code writing, elegance and efficiency can coexist and encourage each other! ! !

reference


维李设论
1.1k 声望4k 粉丝

专注大前端领域发展