Skip to content

Commit

Permalink
refactor(util): simplify snakeToCamel
Browse files Browse the repository at this point in the history
  • Loading branch information
antongolub committed Dec 21, 2024
1 parent ca54f18 commit affd1de
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 10 deletions.
4 changes: 1 addition & 3 deletions src/goods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ export const parseArgv = (
): minimist.ParsedArgs =>
Object.entries(minimist(args, opts)).reduce<minimist.ParsedArgs>(
(m, [k, v]) => {
const kTrans = opts.camelCase
? (k: string) => snakeToCamel(k.replace(/-/, '_'))
: identity
const kTrans = opts.camelCase ? snakeToCamel : identity
const vTrans = opts.parseBoolean ? parseBool : identity
const [_k, _v] = k === '--' || k === '_' ? [k, v] : [kTrans(k), vTrans(v)]
m[_k] = _v
Expand Down
10 changes: 3 additions & 7 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,20 +286,16 @@ export const proxyOverride = <T extends object>(
},
}) as T

// https://stackoverflow.com/a/7888303
export const camelToSnake = (str: string) =>
str
.split(/(?=[A-Z])/)
.map((s) => s.toUpperCase())
.join('_')

// https://stackoverflow.com/a/61375162
export const snakeToCamel = (str: string) =>
str
.toLowerCase()
.replace(/([-_][a-z])/g, (group) =>
group.toUpperCase().replace('-', '').replace('_', '')
)
str.toLowerCase().replace(/([a-z])[_-]+([a-z])/g, (_, p1, p2) => {
return p1 + p2.toUpperCase()
})

export const parseBool = (v: string): boolean | string =>
({ true: true, false: false })[v] ?? v
1 change: 1 addition & 0 deletions test/util.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,5 +145,6 @@ describe('util', () => {
assert.equal(snakeToCamel('NOTHROW'), 'nothrow')
assert.equal(snakeToCamel('PREFER_LOCAL'), 'preferLocal')
assert.equal(snakeToCamel('SOME_MORE_BIG_STR'), 'someMoreBigStr')
assert.equal(snakeToCamel('kebab-input-str'), 'kebabInputStr')
})
})

0 comments on commit affd1de

Please sign in to comment.