Nuxt/packages/nuxi/src/utils/diff.ts

32 lines
1.0 KiB
TypeScript
Raw Normal View History

2021-04-15 19:17:44 +00:00
import flatten from 'flat'
import { detailedDiff } from 'deep-object-diff'
import { green, red, blue, cyan } from 'colorette'
function normalizeDiff (diffObj: any, type: 'added' | 'deleted' | 'updated', ignore: string[]) {
return Object.entries(flatten(diffObj) as Record<string, any>)
2021-04-15 19:17:44 +00:00
.map(([key, value]) => ({ key, value, type }))
.filter(item => !ignore.includes(item.key) && typeof item.value !== 'function')
}
export function diff (a: any, b: any, ignore: string[]) {
2021-04-15 19:17:44 +00:00
const _diff: any = detailedDiff(a, b)
return [
...normalizeDiff(_diff.added, 'added', ignore),
...normalizeDiff(_diff.deleted, 'deleted', ignore),
...normalizeDiff(_diff.updated, 'updated', ignore)
]
2021-04-15 19:17:44 +00:00
}
const typeMap = {
added: green('added'),
deleted: red('deleted'),
updated: blue('updated')
}
export function printDiff (diff: any) {
2021-04-15 19:17:44 +00:00
for (const item of diff) {
console.log(' ', typeMap[item.type as keyof typeof typeMap] || item.type, cyan(item.key), item.value ? `~> ${cyan(item.value)}` : '')
2021-04-15 19:17:44 +00:00
}
console.log()
}