写点什么

ARTS-WEEK9(23.10.9-23.10.15)

作者:EchoZhou
  • 2023-10-16
    上海
  • 本文字数:1318 字

    阅读完需:约 4 分钟

Algorithm 一道算法题

记忆函数,detailhttps://leetcode.cn/problems/memoize-ii/submissions/

type Fn = (...params: any) => any
function memoize(fn: Fn): Fn { const idPool = new Map<unknown, number>() const cache: Map<string, ReturnType<Fn>> = new Map()
return function (...args:Parameters<Fn>): ReturnType<Fn>{ const key = args.map(getId).join(',') const hasKey = cache.has(key) if(hasKey) { return cache.get(key)! }
const res = fn(...args) cache.set(key,res) return res }
function getId(o: unknown): number { const hasO = idPool.has(o) if (hasO) { return idPool.get(o)! } const id = idPool.size idPool.set(o, id) return id }}
复制代码


Review 读一篇英文文章

Beauty Is in Simplicity

https://97-things-every-x-should-know.gitbooks.io/97-things-every-programmer-should-know/content/en/thing_05/


Technique/Tips 分享一个小技术

What's the difference between useState and useReducer

  • api 不一样,useState 适用于简单的单个组建的场景,useReducer 使用更为复杂的状态。

// 没有jsx的编辑模式 暂用JavaScript代替import { useState } from 'react'// useStatefunction ToggleButton() {  const [isToggled, setIsToggled] = useState(false)
function handleClick() { setIsToggled(!isToggled) }
return <button onClick={handleClick}>{isToggled ? 'ON' : 'OFF'}</button>}
import { useReducer } from 'react'
const initialState = { count: 0 }
function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 } case 'decrement': return { count: state.count - 1 } default: throw new Error() }}// useReducerfunction Counter() { const [state, dispatch] = useReducer(reducer, initialState)
return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> </div> )}
复制代码


import {useState, useReducer} from "react";
const third = (x) => x;
export default function App() { const [first, setFirst] = useState(0); const [second, setSecond] = useReducer((x) => x, 0, third);
console.log("render"); //sy-log
return ( <div className="App"> <button onClick={() => setFirst(0)}>first:{first}</button> <button onClick={() => setSecond(0)}>second: {second}</button> </div> );}
复制代码


Share 分享一个观点

If you can SAY it, you can HEAR it. --- Coach Shane


用户头像

EchoZhou

关注

还未添加个人签名 2018-04-24 加入

还未添加个人简介

评论

发布
暂无评论
ARTS-WEEK9(23.10.9-23.10.15)_EchoZhou_InfoQ写作社区