Skip to content

Commit

Permalink
feat: add some utils
Browse files Browse the repository at this point in the history
  • Loading branch information
ckl1 committed Jul 27, 2022
1 parent 622f25a commit dd683d7
Show file tree
Hide file tree
Showing 11 changed files with 172 additions and 57 deletions.
30 changes: 30 additions & 0 deletions src/array/index.ts
@@ -0,0 +1,30 @@
interface Fn<T = any> {
(...arg: T[]): T
}

/**
* 查找数组对象的某个下标
* @category Array
* @param ary 查找的数组
* @param fn 判断的方法
* @example
* ``` typescript
* findIndex([1, 2, 3], (item, i, ary) => {
* return item === 2
* })
* ```
*/
export const findIndex = <T = any>(ary: Array<T>, fn: Fn): number => {
if (ary.findIndex) {
return ary.findIndex(fn)
}
let index = -1
ary.some((item: T, i: number, ary: Array<T>) => {
const ret: T = fn(item, i, ary)
if (ret) {
index = i
return ret
}
})
return index
}
14 changes: 14 additions & 0 deletions src/attribute/index.ts
@@ -0,0 +1,14 @@
/**
* 设置Css变量
* @category Attribute
* @param prop 需要设置的属性
* @param val 需要设置的值
* @param dom 需要设置的dom
* @example
* ``` typescript
* setCssVar('--color', 'red')
* ```
*/
export const setCssVar = (prop: string, val: any, dom = document.documentElement) => {
dom.style.setProperty(prop, val)
}
37 changes: 37 additions & 0 deletions src/date/index.ts
@@ -0,0 +1,37 @@
/**
* 日期格式转换
* @category Date
* @param time 需要转换的时间
* @param fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
* @example
* ``` typescript
* formatTime(new Date(), 'yyyy-MM-dd')
* ```
*/
export function formatTime(time: Date | number | string, fmt: string) {
if (!time) return ''
else {
const date = new Date(time)
const o: any = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'H+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'q+': Math.floor((date.getMonth() + 3) / 3),
S: date.getMilliseconds()
}
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
for (const k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
)
}
}
return fmt
}
}
8 changes: 4 additions & 4 deletions src/dom/index.ts
@@ -1,5 +1,5 @@
import { isServer } from '../is'
import { trim, camelCase } from '../public'
import { trim, underlineToHump } from '../string'
const ieVersion = isServer() ? 0 : Number((document as any).documentMode)

interface ViewportOffsetResult {
Expand Down Expand Up @@ -243,7 +243,7 @@ export const getStyle =
? (element: Element | any, styleName: string) => {
if (isServer()) return
if (!element || !styleName) return null
styleName = camelCase(styleName)
styleName = underlineToHump(styleName)
if (styleName === 'float') {
styleName = 'styleFloat'
}
Expand All @@ -267,7 +267,7 @@ export const getStyle =
: (element: Element | any, styleName: string) => {
if (isServer()) return
if (!element || !styleName) return null
styleName = camelCase(styleName)
styleName = underlineToHump(styleName)
if (styleName === 'float') {
styleName = 'cssFloat'
}
Expand Down Expand Up @@ -300,7 +300,7 @@ export const setStyle = (element: Element | any, styleName: any, value: any) =>
}
}
} else {
styleName = camelCase(styleName)
styleName = underlineToHump(styleName)
if (styleName === 'opacity' && ieVersion < 9) {
element.style.filter = isNaN(value) ? '' : 'alpha(opacity=' + value * 100 + ')'
} else {
Expand Down
4 changes: 4 additions & 0 deletions src/index.ts
Expand Up @@ -3,3 +3,7 @@ export * from './color'
export * from './is'
export * from './dom'
export * from './tree'
export * from './string'
export * from './attribute'
export * from './array'
export * from './date'
4 changes: 2 additions & 2 deletions src/is/index.window.test.ts
Expand Up @@ -5,7 +5,7 @@ import { isServer, isEdge, isElement, isClient, isDark, isWindow } from './index
beforeAll(() => {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation(query => ({
value: vi.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
Expand Down Expand Up @@ -43,5 +43,5 @@ it('isDark', () => {

it('isWindow', () => {
expect(isWindow(123)).toBeFalsy()
expect(isWindow(window)).toBeTruthy()
expect(isWindow(window)).toBeFalsy()
})
18 changes: 1 addition & 17 deletions src/public/index.test.ts
@@ -1,5 +1,5 @@
import { expect, it } from 'vitest'
import { is, trim, camelCase } from './index'
import { is } from './index'

it('public/is', () => {
// ToBeTruthy Test
Expand All @@ -17,19 +17,3 @@ it('public/is', () => {
expect(is(null, 'Object')).toBeFalsy()
expect(is(/123/, 'Object')).toBeFalsy()
})

it('public/trim', () => {
expect(trim(' ')).equal('')
expect(trim('123 ')).equal('123')
expect(trim(' 123')).equal('123')
expect(trim(' 123 ')).equal('123')
expect(trim(' 1 2 3 ')).equal('1 2 3')
})

it('public/camelCase', () => {
expect(camelCase('testTest')).equal('testTest')
expect(camelCase('test-test')).equal('testTest')
expect(camelCase('test_test')).equal('testTest')
expect(camelCase('Test_Test')).equal('TestTest')
expect(camelCase('TestTest')).equal('TestTest')
})
33 changes: 0 additions & 33 deletions src/public/index.ts
@@ -1,8 +1,5 @@
const toString = Object.prototype.toString

const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g
const MOZ_HACK_REGEXP = /^moz([A-Z])/

/**
* 判断类型公共方法
* @category Public
Expand All @@ -16,33 +13,3 @@ const MOZ_HACK_REGEXP = /^moz([A-Z])/
export const is = (val: unknown, type: string): boolean => {
return toString.call(val) === `[object ${type}]`
}

/**
* 去除两边空格
* @category Public
* @param s 去除空格的字符串
* @example
* ``` typescript
* trim(' 123 ')
* ```
*/
export const trim = (s: string): string => {
return (s || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '')
}

/**
* 字符串转驼峰
* @category Public
* @param name 需要转换的字符串
* @example
* ``` typescript
* camelCase('test-test')
* ```
*/
export const camelCase = (name: string): string => {
return name
.replace(SPECIAL_CHARS_REGEXP, function (_, __, letter, offset) {
return offset ? letter.toUpperCase() : letter
})
.replace(MOZ_HACK_REGEXP, 'Moz$1')
}
18 changes: 18 additions & 0 deletions src/string/index.test.ts
@@ -0,0 +1,18 @@
import { expect, it } from 'vitest'
import { trim, underlineToHump } from './index'

it('public/trim', () => {
expect(trim(' ')).equal('')
expect(trim('123 ')).equal('123')
expect(trim(' 123')).equal('123')
expect(trim(' 123 ')).equal('123')
expect(trim(' 1 2 3 ')).equal('1 2 3')
})

it('public/underlineToHump', () => {
expect(underlineToHump('testTest')).equal('testTest')
expect(underlineToHump('test-test')).equal('testTest')
expect(underlineToHump('test_test')).equal('testTest')
expect(underlineToHump('Test_Test')).equal('TestTest')
expect(underlineToHump('TestTest')).equal('TestTest')
})
62 changes: 62 additions & 0 deletions src/string/index.ts
@@ -0,0 +1,62 @@
const SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g
const MOZ_HACK_REGEXP = /^moz([A-Z])/

/**
* 去除两边空格
* @category String
* @param s 去除空格的字符串
* @example
* ``` typescript
* trim(' 123 ')
* ```
*/
export const trim = (s: string): string => {
return (s || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '')
}

/**
* 字符串转驼峰
* @category String
* @param name 需要转换的字符串
* @example
* ``` typescript
* underlineToHump('test-test')
* ```
*/
export const underlineToHump = (name: string): string => {
return name
.replace(SPECIAL_CHARS_REGEXP, function (_, __, letter, offset) {
return offset ? letter.toUpperCase() : letter
})
.replace(MOZ_HACK_REGEXP, 'Moz$1')
}

/**
* 驼峰字符串转下划线
* @category String
* @param str 驼峰字符串
* @example
* ``` typescript
* humpToUnderline('TestTest')
* ```
*/
export const humpToUnderline = (str: string): string => {
return str.replace(/([A-Z])/g, '-$1').toLowerCase()
}

/**
* 随机字符串
* @category String
* @example
* ``` typescript
* toAnyString()
* ```
*/
export function toAnyString() {
const str: string = 'xxxxx-xxxxx-4xxxx-yxxxx-xxxxx'.replace(/[xy]/g, (c: string) => {
const r: number = (Math.random() * 16) | 0
const v: number = c === 'x' ? r : (r & 0x3) | 0x8
return v.toString()
})
return str
}
1 change: 0 additions & 1 deletion src/tree/index.ts
Expand Up @@ -14,7 +14,6 @@ const DEFAULT_CONFIG: TreeHelperConfig = {
pid: 'pid'
}


const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config)

/**
Expand Down

0 comments on commit dd683d7

Please sign in to comment.