Skip to content

Commit

Permalink
feat: 增加示例
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jun 2, 2019
1 parent 3827577 commit 0fc4767
Show file tree
Hide file tree
Showing 50 changed files with 1,258 additions and 145 deletions.
598 changes: 580 additions & 18 deletions README.md

Large diffs are not rendered by default.

60 changes: 60 additions & 0 deletions src/EasyValidator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,63 @@ test('综合测试', async () => {
},
)
})

test('示例', async () => {
async function checkPhoneNumberAsync(_num: string) {
await wait(500)
return {
valid: true,
message: '',
}
}
interface Data {
name: string,
phoneNumber: string,
pass1: string,
pass2: string,
}
const ev = new EasyValidator<Data>([
{
key: 'name',
type: 'chineseName',
message: '请输入真实姓名',
},
{
key: 'phoneNumber',
type: 'chineseMobilePhoneNumber',
message: '请输入正确的手机号码',
},
{
key: 'phoneNumber',
test: async ({ phoneNumber }, { updateMessage }) => {
const result = await checkPhoneNumberAsync(phoneNumber)
if (!result.valid) {
updateMessage(result.message)
return false
}
},
message: '请输入正确的手机号码',
},
{
key: 'pass1',
test: ({ pass1 }) => pass1.length > 6,
message: '密码应大于6位',
},
{
key: 'pass2',
test: ({ pass1, pass2 }) => pass2 === pass1,
message: '两次密码应一致',
},
])
const res = await ev.validate({
name: '方一一',
phoneNumber: '18087030070',
pass1: '1234567',
pass2: '12345678',
})
expect(res.valid).toBeFalsy()
jestExpectEqual(
res.unvalidRules[0].key,
'pass2',
)
})
42 changes: 34 additions & 8 deletions src/EasyValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,27 +76,53 @@ export interface EasyValidatorValidateReturn<D extends EasyValidatorData> {
* pass2: string,
* }
* const ev = new EasyValidator<Data>([
* { key: 'name', type: 'chineseName', message: '请输入真实姓名' },
* { key: 'phoneNumber', type: 'chineseMobilePhoneNumber', message: '请输入正确的手机号码' },
* {
* key: 'name',
* type: 'chineseName',
* message: '请输入真实姓名',
* },
* {
* key: 'phoneNumber',
* type: 'chineseMobilePhoneNumber',
* message: '请输入正确的手机号码',
* },
* {
* key: 'phoneNumber',
* test: async (phoneNumber) => {
* test: async ({ phoneNumber }, { updateMessage }) => {
* const result = await checkPhoneNumberAsync(phoneNumber)
* if (result.pass) return true
*
* if (!result.valid) {
* updateMessage(result.message)
* return false
* }
* },
* message: '请输入正确的手机号码'
* },
* { key: 'pass1', test: pass1 => pass1.length > 6, message: '密码应大于6位' },
* { key: 'pass2', test: (pass2, data) => pass2 === data.pass1, message: '两次密码应一致' },
* {
* key: 'pass1',
* test: ({ pass1 }) => pass1.length > 6,
* message: '密码应大于6位',
* },
* {
* key: 'pass2',
* test: ({ pass1, pass2 }) => pass2 === pass1,
* message: '两次密码应一致',
* },
* ])
* ev.validate({
* name: '方一一',
* phoneNumber: '18087030070',
* pass1: '1234567',
* pass2: '12345678'
* }).then(res => {
* // => { valid: false, unvalidRules: [{ key: 'pass2', test: ({ pass1, pass2 }) => pass2 === pass1, message: '两次密码应一致' }] }
* })
* ```
*/
export class EasyValidator<D extends EasyValidatorData> {
/**
* 构造函数。
*
* @param rules 规律列表
* @param rules 规则列表
*/
constructor(private rules: EasyValidatorRules<D>) {}

Expand Down
17 changes: 17 additions & 0 deletions src/EventBus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@ export type EventBusUnsubscribe = () => void
* 事件巴士,管理事件的发布与订阅。
*
* @template T 事件名称及其对应的监听器描述
* @example
* ```ts
* const bus = new EventBus<{
* success: () => void,
* error: (message: string) => void,
* }>()
* const unbindSuccessListener = bus.on('success', () => {
* console.log('成功啦')
* })
* const unbindErrorListener = bus.once('error', message => {
* console.error(message)
* })
* bus.emit('success')
* bus.emit('error', '出错啦')
* unbindSuccessListener()
* bus.off('error')
* ```
*/
export class EventBus<
T extends Record<string, AnyFunction> = Record<string, AnyFunction>,
Expand Down
17 changes: 17 additions & 0 deletions src/Wechat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,23 @@ const shareJsApiList: WechatJsApi[] = [

/**
* 对微信 JSSDK 的封装。
*
* @example
* ```ts
* const wechat = new Wechat()
* getWechatConfigAsync().then(config => {
* wechat.config(config)
* })
* wechat.updateShareData({
* title: '分享标题',
* desc: '分享描述',
* link: '分享链接',
* imgUrl: '缩略图地址',
* })
* wechat.invoke('scanQRCode').then(res => {
* // => API 调用结果
* })
* ```
*/
export class Wechat {
/**
Expand Down
3 changes: 2 additions & 1 deletion src/assign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import { forOwn } from './forOwn'
* { x: 1 },
* { y: 2 },
* { x: 5, z: 9 },
* ) // => { x: 5, y: 2, z: 9 }
* )
* // => { x: 5, y: 2, z: 9 }
* ```
*/
export function assign<T extends object>(target: T, ...sources: object[]): T {
Expand Down
22 changes: 15 additions & 7 deletions src/chunk.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,34 @@
import { isFunction, isPositiveInteger } from './is'

/**
* 将 `array` 拆分成多个 `size` 长度的区块,并将它们组合成一个新数组返回。
* 将 `arr` 拆分成多个 `size` 长度的区块,并将它们组合成一个新数组返回。
*
* 如果 `array` 无法等分,且设置了 `filler`,剩余的元素将被 `filler` 填充
* 如果 `arr` 无法等分,且设置了 `filler` 函数,剩余的元素将被 `filler` 函数的返回值填充
*
* @param array 要处理的数组
* @param arr 要处理的数组
* @param size 每个区块的长度
* @param filler 返回填充物的函数,其接收当前填充物的索引,即第几个填充物(从 `0` 开始),并返回填充物
* @returns 返回拆分后的新数组
* @example
* ```ts
* const arr = [1, 2, 3, 4, 5, 6]
* chunk(arr, 2) // => [[1, 2], [3, 4], [5, 6]]
* chunk(arr, 3) // => [[1, 2, 3], [4, 5, 6]]
* chunk(arr, 4) // => [[1, 2, 3, 4], [5, 6]]
* chunk(arr, 4, index => index) // => [[1, 2, 3, 4], [5, 6, 0, 1]]
* ```
*/
export function chunk<T>(array: T[], size: number, filler?: (index: number) => T): T[][] {
export function chunk<T>(arr: T[], size: number, filler?: (index: number) => T): T[][] {
if (!isPositiveInteger(size)) {
throw new RangeError('size 应为正整数')
}
if (array.length === 0) {
if (arr.length === 0) {
return []
}
const result: T[][] = []
const rows = Math.ceil(array.length / size)
const rows = Math.ceil(arr.length / size)
for (let i = 0; i < rows; i++) {
result.push(array.slice(i * size, (i + 1) * size))
result.push(arr.slice(i * size, (i + 1) * size))
}
const lastRow = result[rows - 1]
if (arguments.length === 3 && lastRow.length < size) {
Expand Down
7 changes: 7 additions & 0 deletions src/clamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@
* @param min 最小值
* @param max 最大值
* @returns 返回结果值
* @example
* ```ts
* clamp(50, 0, 100) // => 50
* clamp(50, 0, 50) // => 50
* clamp(50, 0, 49) // => 49
* clamp(50, 51, 100) // => 51
* ```
*/
export function clamp(value: number, min: number, max: number): number {
return (
Expand Down
26 changes: 0 additions & 26 deletions src/column.test.ts

This file was deleted.

35 changes: 0 additions & 35 deletions src/column.ts

This file was deleted.

5 changes: 5 additions & 0 deletions src/endsWith.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
* @param str 要检查的字符串
* @param needle 要检索的字符串
* @returns `str` 以 `needle` 结尾返回 `true`,否则返回 `false`
* @example
* ```ts
* endsWith('hello', 'llo') // => true
* endsWith('hello', 'he') // => false
* ```
*/
export function endsWith(str: string, needle: string): boolean {
return str.endsWith ? str.endsWith(needle) : str.slice(-needle.length) === needle
Expand Down
12 changes: 12 additions & 0 deletions src/enhanceType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ export type LiteralUnion<L, B> = L | Brand<B, never>

export type IsNever<T> = [T] extends [never] ? true : false

/**
* 条件类型。
*
* @example
* ```ts
* type X = 'x'
* // before
* type IsX = X extends 'x' ? true : false
* // after
* type IsX = If<X extends 'x', true, false>
* ```
*/
export type If<Condition, Then, Else> = Condition extends true ? Then : Else

/**
Expand Down
22 changes: 22 additions & 0 deletions src/env.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,28 @@ const tests: Record<keyof typeof env, (_: typeof env) => void> = {
)
},

inAndroid({ inAndroid }) {
jestExpectEqual(
inAndroid(),
false,
)

const originalUA = navigator.userAgent
Object.defineProperty(navigator, 'userAgent', {
value: 'Android',
writable: true,
})
inAndroid.clearCache()
jestExpectEqual(
inAndroid(),
true,
)
Object.defineProperty(navigator, 'userAgent', {
value: originalUA,
writable: true,
})
},

inNode({ inNode }) {
jestExpectEqual(
inNode(),
Expand Down
Loading

0 comments on commit 0fc4767

Please sign in to comment.