Giter Site home page Giter Site logo

awesome-exercises's People

Contributors

coolpail avatar

Stargazers

 avatar

Watchers

 avatar  avatar

awesome-exercises's Issues

利用类似effect去发送请求

function lastPromise(promiseFn) {
  let resetReturn;
  return function () {
    let cancel = false;
    if (resetReturn) resetReturn();
    resetReturn = () => cancel = true
    return new Promise((resolve) => {
      promiseFn().then((res) => !cancel && resolve(res))
    })
  }
}

let count = 1
let fn = () => new Promise(rs => setTimeout(() => rs(count++)))

let lastGn = lastPromise(fn)

lastGn().then(console.log)
lastGn().then(console.log)
lastGn().then(console.log)
  1. 首先闭包一个resetReturn
  2. 每次闭包进一个独立的cancel,

useEffect 获取之前的值

function usePrevious(value) {
  const ref = useRef()
  useEffect(() => {
    ref.current = value
  }, [value])
  return ref.current
}

手写flat

利用concat入参是数组时,相当于自动铺平一层

方法一:

function myFlat(arr) {
   let result = [];
   for(let i = 0; i < arr.length; i++) {
     if (Array.isArray(arr[i])) result = result.concat(myFlat(arr[i]))
     else result = result.concat(arr[i])
   }
   return result;
}

方法二:

function myFlat(arr) {
  return arr.reduce((p, n) => p.concat(Array.isArray(n) ? myFlat(n) : n), []);
}

练习题1-树形相关

题目

以下数据结构中,id 代表部门编号,name 是部门名称,parentId 是父部门编号,
为 0 代表一级部门,现在要求实现一个 convert 方法,
把原始 list 转换成树形结构,parentId 为多少就挂载在该 id 的属性 children 数组下,结构如下:
// 原始 list 如下
let list =[
{id:1,name:'部门A',parentId:0},
{id:2,name:'部门B',parentId:0},
{id:3,name:'部门C',parentId:1},
{id:4,name:'部门D',parentId:1},
{id:5,name:'部门E',parentId:2},
{id:6,name:'部门F',parentId:3},
{id:7,name:'部门G',parentId:2},
{id:8,name:'部门H',parentId:4}
];
const result = convert(list, ...);

// 转换后的结果如下
let result = [
    {
      id: 1,
      name: '部门A',
      parentId: 0,
      children: [
        {
          id: 3,
          name: '部门C',
          parentId: 1,
          children: [
            {
              id: 6,
              name: '部门F',
              parentId: 3
            }, {
              id: 16,
              name: '部门L',
              parentId: 3
            }
          ]
        },
        {
          id: 4,
          name: '部门D',
          parentId: 1,
          children: [
            {
              id: 8,
              name: '部门H',
              parentId: 4
            }
          ]
        }
      ]
    },
  ···
];

思路

  1. 观察到id是按顺序排序的
  2. 由题可知parentId是按id查找的
  3. 所以id === index === parentId
  4. 逆序操作,末尾添加到前面,然后删除当前
let len = list.length;
for (let i = len - 1; i >= 0; i--) {
    let item = list[i];
    let parentId = item.parentId;
    if (list[parentId - 1]) {
        if (list[parentId - 1].children) {
            list[parentId - 1].children.push(list[i]);
        } else list[parentId - 1].children = [list[i]];
        list.splice(i, 1);
    }
}

练习题2-树形相关

题目

//输入以下有序的list数组
var list = [
    'h3',
    'h2', 'h3',
    'h1', 'h2', 'h3', 'h3', 'h2', 'h3',
    'h1', 'h2', 'h4', 'h2', 'h3',s
]
//输出以下树形数组结构
[
    {
        name: 'h3',
        child: []
    },
    {
        name: 'h2',
        child: [{name: 'h3'}]
    },
    {
        name: 'h1',
        child: [
            {
                name: 'h2',
                child: [{name: 'h3'}, {name: 'h3'}]
            },
            {
                name: 'h2',
                child: [{name: 'h3'}]
            }
        ]
    },
    {
        name: 'h1',
        child: [
            {
                name: 'h2',
                child: [{name: 'h4'}]
            },
            {
                name: 'h2',
                child: [{name: 'h3'}]
            }
        ]
    }
]

思路

  1. 独立维护一份数组list
  2. 每次push时,先判断list的最后一个元素,是否比当前要push的元素大,则list元素pop出最后一个,在比较;小则当前最后一个元素的child中添加进该元素,并且list数组push进该元素
let stacks = [];

function createNode(key) {
    return {
        name: key,
        child: []
    }
}

function task(node, key) {
    stacks.push({
        name: key,
        node: node
    })
}

function Compare(k1, k2) {
    return Number(k1.slice(1)) <= Number(k2.slice(1))
}

function insert(el) {
    let _t = stacks[stacks.length - 1];
    if (!stacks.length) {
        let newnode = createNode(el);
        result.push(newnode);
        task(newnode, el);
    } else {
        if (Compare(el, _t.name)) {
            stacks.pop();
            insert(el)
        } else {
            let newnode = createNode(el);
            _t.node.child.push(newnode);
            task(newnode, el);
        }
    }
}

let list = []
let total = 1000000
for(let i = 0; i < total; i++) {
    list.push('h' + Math.floor(Math.random() * 10 + 1))
}

let result = []
list.forEach(insert);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.