Symbol
ES6 引入了一种新的原始数据类型 Symbol,表示独一无二的值。
Symbol 值通过 Symbol 函数生成,也就是说,对象的属性名现在可以有两种类型:一种是字符串,另一种就是 Symbol 类型。只要属性名属于 Symbol 类型,就是独一无二的,可以保证不会与其他属性名冲突。
1 | let s = Symbol() |
Symbol 函数可以接受一个字符串作为参数,表示对 Symbol 实例的描述,主要是为了在 console 显示。
1 | let s = Symbol("str") |
如果 Symbol 的参数是一个对象,就会调用该对象的 toString 方法,再生成 Symbol 值
1 | const obj = { |
State/Effect 分层
友好的 React Hooks
网络上对 react hooks 的评价负面大于正面,确实很容易写出性能有问题的代码,关键就在于:我们太喜欢用 useState 了。
在 vue-composition-api 中,reactivity 数据都有 wrapper,custom-vca 里不管产生多少个 reactivity 对象,不会直接产生 re-render。只有那些被 return 到外部跟 template 绑定的部分才会触发视图渲染。
而 react 的 reactivity 就是通过 re-render 实现的,useState 没有 wrapper,每次使用都会得到一个触发渲染的函数。在这种 reactivity 机制下,就需要特殊的方式编写 hooks —— State/Effect 分层
假设有个 useHeight:
1 | const [ref, height] = useHeight() |
高度变化时,被动 re-render,难以转换合并。大部分情况下,不提供 state,而提供 effect 可能会更好:
1 | const [height, setHeight] = useState(0) |
使用者在外部声明 state,然后在 callback 中按需 setState。使用者可以结合其他 state,做 dispatch 到 reducer 的一次整体更新,而不是被动 re-render。
根据 State/Effect 分层理念,尝试着给出友好地 react hooks 公式:
1 | const handler = useProducer(consumer, options) |
producer 接收 consumer callback 作为参数,返回 handler 控制函数,用于绑定到事件或其他位置。
Telegram批量邀请成员进组
The composition
Function Composition
In computer science, function composition is an act or mechanism to combine simple functions to build more complicated ones. Like the usual composition of functions in mathematics, the result of each function is passed as the argument of the next, and the result of the last one is the result of the whole. -- Wikipedia
Example:
1 | var compose = (f, g) => (x) => f(g(x)) |
In the definition of compose, g will be executed before f, thus creating a right-to-left data stream. This is much more readable than nesting a bunch of function calls.
Associativity
Like many other functional programming concepts, associativity is derived from math.It is an expression in which the order of evaluation does not affect the end result provided the sequence of the operands does not get changed. -- JOSEPH REX
Example:
1 | 2 + (3 + 4) === 2 + 3 + 4 // true |
Because of the grouping of calls to compose is not important, so the result is the same. This also gives us the ability to write a variadic compose.
Like this:
1 | var last = compose(head, reverse) |
There is no standard answer on how to composition, just make it more reusable.