Skip to content

Commit

Permalink
feat: add toPath
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Nov 1, 2018
1 parent 1e24054 commit a769c68
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export { default as Disposer } from './Disposer'
export { default as base64Decode } from './base64Decode'
export { default as base64Encode } from './base64Encode'
export { default as base64UrlDecode } from './base64UrlDecode'
Expand All @@ -8,6 +7,7 @@ export { default as castArray } from './castArray'
export { default as clamp } from './clamp'
export { default as cssTransform } from './cssTransform'
export { default as currencyFormat } from './currencyFormat'
export { default as Disposer } from './Disposer'
export { default as fill } from './fill'
export { default as forOwn } from './forOwn'
export { default as getType } from './getType'
Expand Down Expand Up @@ -49,5 +49,6 @@ export { default as stopEventPropagation } from './stopEventPropagation'
export { default as storage } from './storage'
export { default as supportPassiveEventListener } from './supportPassiveEventListener'
export { default as toDate } from './toDate'
export { default as toPath } from './toPath'
export { default as upperCaseFirst } from './upperCaseFirst'
export { default as values } from './values'
33 changes: 33 additions & 0 deletions src/toPath.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const cache = Object.create(null)

/**
* 转化 `value` 为属性路径的数组 。
*
* @param value 要转换的值
* @returns 包含属性路径的数组
*/
export default function toPath(value: string): string[] {
const path: string[] = []
for (
let prev = 0, cur = 0, stop = null, len = value.length;
cur < len;
) {
const curChar = value[cur]
if (
(cur === len - 1) ||
(stop === null ? (curChar === '.' || curChar === '[') : curChar === stop)
) {
if (cur === len - 1) {
path.push(value.substring(prev, curChar === ']' ? cur : cur + 1))
} else if (prev !== cur) {
path.push(value.substring(prev, cur))
}
stop = curChar === '.' ? null :
curChar === '[' ? ']' :
null
prev = cur + 1
}
cur++
}
return path
}
8 changes: 8 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -935,3 +935,11 @@ describe('toDate', () => {
})
})
})

describe('toPath', () => {
test('ok', () => {
expect(vtils.toPath('ss.dee.3.dew.22')).toEqual(['ss', 'dee', '3', 'dew', '22'])
expect(vtils.toPath('ss.dee[3].dew.22[we]')).toEqual(['ss', 'dee', '3', 'dew', '22', 'we'])
expect(vtils.toPath('dee[3.2][hello.333]')).toEqual(['dee', '3.2', 'hello.333'])
})
})

0 comments on commit a769c68

Please sign in to comment.