Skip to content

Commit

Permalink
feat: add recursive support
Browse files Browse the repository at this point in the history
  • Loading branch information
p-chan committed Feb 12, 2022
1 parent 1180879 commit f827d35
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 25 deletions.
27 changes: 2 additions & 25 deletions src/action.ts
Expand Up @@ -4,11 +4,7 @@ import { TsConfigJson } from 'type-fest'
import consola from 'consola'
import prettier from 'prettier'

import { order } from './order'

type Object = {
[key: string]: any
}
import { sort } from './sort'

type Options = {
'--': any[]
Expand All @@ -34,26 +30,7 @@ export const action = async (options: Options) => {

if (tsConfigJson.compilerOptions == undefined) throw new Error('compilerOptions is not defined')

const nextCompilerOptions: Object = {}

Object.keys(tsConfigJson.compilerOptions)
.sort((a, b) => {
let aIndex = order.findIndex((key) => key === a)
let bIndex = order.findIndex((key) => key === b)

aIndex = aIndex >= 0 ? aIndex : Number.MAX_SAFE_INTEGER
bIndex = bIndex >= 0 ? bIndex : Number.MAX_SAFE_INTEGER

if (aIndex > bIndex) return 1
if (aIndex < bIndex) return -1

return 0
})
.forEach((key) => {
nextCompilerOptions[key] = (tsConfigJson.compilerOptions as Object)[key]
})

tsConfigJson.compilerOptions = nextCompilerOptions
tsConfigJson.compilerOptions = sort(tsConfigJson.compilerOptions, 0)

const tsConfigJsonString = JSON.stringify(tsConfigJson)

Expand Down
75 changes: 75 additions & 0 deletions src/sort.ts
@@ -0,0 +1,75 @@
import { order } from './order'

type Array = any[]

type Object = {
[key: string]: any
}

export const sort = (target: any, depth: number) => {
// array
if (Array.isArray(target)) {
const array = target
const nextArray: Array = []

array
.sort((a, b) => {
if (a < b) return -1
if (a > b) return 1

return 0
})
.forEach((item) => {
if (Array.isArray(item) || typeof item === 'object') {
return sort(item, depth + 1)
}

return nextArray.push(item)
})

return nextArray
}

// object
if (typeof target === 'object') {
const object = target
const nextObject: Object = {}

Object.keys(object)
.sort((a, b) => {
// compilerOptions
if (depth === 0) {
let aIndex = order.findIndex((key) => key === a)
let bIndex = order.findIndex((key) => key === b)

aIndex = aIndex >= 0 ? aIndex : Number.MAX_SAFE_INTEGER
bIndex = bIndex >= 0 ? bIndex : Number.MAX_SAFE_INTEGER

if (aIndex > bIndex) return 1
if (aIndex < bIndex) return -1

return 0
}

// others
if (a < b) return -1
if (a > b) return 1

return 0
})
.forEach((key) => {
return (nextObject[key] = (() => {
if (Array.isArray(object[key]) || typeof object[key] === 'object') {
return sort(object[key], depth + 1)
}

return object[key]
})())
})

return nextObject
}

// no sortable
return target
}

0 comments on commit f827d35

Please sign in to comment.