@ frecle/ 也许
提供可能类型操作的帮助函数集合 .
动机
这个软件包试图重现在强烈打入的功能编程语言中常见的idioms,并受到来自 数据 也许哈斯凯尔包。 。 。 .
安装
pnpm add @freckle/maybe
此套装仅限无害环境管理("type": "module") (中文(简体) ). 偏爱 import。 。 。 . require('@freckle/maybe')
在22.12+节点上工作 require(esm),但不能在更古老的节点 或仅由CJS捆绑.
使用量
业务是用来完善一项可能的投入 null 或者说 undefined数字 :
import {fromJust, fromMaybe, maybe} from '@freckle/maybe'
// Return input from a user, if any:
declare function getUserInput(): ?string
const mUserInput = getUserInput()
// Go from ?string -> string:
const input = fromMaybe(() => 'No input', mUserInput)
// Run a function on ?string with a default:
const capitalized = maybe(() => 'No input to capitalize', capitalize, mUserInput)
// Or produce an error on null | undefined to make future execution more predictable:
const userInput = fromJust(mUserInput, 'No input was given!')
其他行动可能携带 null 应用函数后的值 :
import {mmap, mthen} from '@freckle/maybe'
// Return input from a user, if any:
declare function getUserInput(): ?string
// Function that does not handle a null | undefined value:
declare function transform(input: string): string
const mUserInput = getUserInput()
const mTransformed = mmap(transform, mUserInput)
// => null | undefined | transform(mUserInput)
// Alternate form that is more helpful for control flow:
mthen(mTransformed, (transformedUserInput: string) => {
// Process value
})
用于处理可能包含的阵列 null 或者说 undefined 要素 :
import {catMaybes, mapMaybes} from '@freckle/maybe'
const arr = [
null,
'foo',
undefined,
'bar'
]
const out = catMaybes(arr)
console.log(out) // => ['foo', 'bar']
const padString = (input: string) => ` ${input}`
const mapped = mapMaybes(arr, padString)
console.log(mapped) // => [' foo', ' bar']
有两个操作被定制用于React:
import {mEffect, asHTMLAttributeValue} from '@freckle/maybe'
type Props = {
myInput: ?string
}
const MyComponent = (props: Props): React.Node => {
// This prop may be string | undefined | null
const possibleInput = props.myInput
React.useEffect(() => {
mEffect(possibleInput, input =>
// Call a side effect that does not handle a null value:
sideEffect(input)
)
}, [possibleInput])
// Rendering an element with an attribute from a maybe value:
const attrObj = {'my-attribute': asHTMLAttributeValue(possibleInput)}
// If input is not a string, <div> is rendered;
// otherwise: <div my-attribute="..." />
return <div {...attrObj} />
}
发展
- 软件包管理器: pnpm(节点版本被钉入)
.nvmrc(中文(简体) ) pnpm build—— 说tsc,发送到dist/pnpm test- 维特pnpm coverage- 覆盖率为70%的Vitest(线路/行/功能/说明)pnpm typecheck—— 说tsc --noEmit,包括测试文件pnpm lint——ESLint公司pnpm format编号 :pnpm format-check- 更高级pnpm knip——未用文件/依赖/导出- CI在每份公关上 都查了一下
dist/最新数据
释放
见 发 言 更多细节.