Skip to content

Instantly share code, notes, and snippets.

@slugbyte
Created December 30, 2018 19:18
Show Gist options
  • Save slugbyte/9a4eb6e0615cb51fa7502a4bc1f6c30b to your computer and use it in GitHub Desktop.
Save slugbyte/9a4eb6e0615cb51fa7502a4bc1f6c30b to your computer and use it in GitHub Desktop.
const {get, cloneDeep} = require('lodash/fp')
// A TERRIBLE SIN I KNOW
let oldLog = console.log.bind(console)
console.log = (...args) => {
args = args.map(i => i.isValueHistory ? i.get() : i)
return oldLog(...args)
}
let valueHistory = (name='tracker') => {
let history = []
let state = null
return new Proxy({
isValueHistory: true,
get: () => state,
getHistory: () => history,
set: (value) => {
state = value
history.push(cloneDeep(value))
return value
},
toHistoryString: (options={}) => {
options.join = options.join || '\n'
options.indent = options.indent || ''
return options.indent + history
.map((item, index) => {
let pre = name + ' ' + index + ': '
if(typeof item === 'object' && options.path){
return pre + JSON.stringify(get(options.path, item))
}
return pre + JSON.stringify(item)
})
.join(options.join + options.indent)
},
clearHistory: () => {
history = []
},
},{
set: (target, prop, value) => {
let result = cloneDeep(state)
result[prop] = value
history.push(result)
state[prop] = value
return
},
get: (target, prop, caller) => {
if(target[prop]) return target[prop]
return target.get()[prop]
},
deleteProperty: (target, prop) => {
let result = cloneDeep(target.get())
delete result[prop]
history.push(result)
delete state[prop]
},
ownKeys: (target) => {
return Reflect.ownKeys(target.get())
}
})
}
let wat = valueHistory('wat')
wat.set({content: 'cool beans', user: 'gort_4567'})
wat.user = 'hello'
wat.user = 'roman'
delete wat.user
wat.user = 'dork'
wat.user = 'beans'
console.log(wat.toHistoryString())
console.log('wat.user', wat.user)
console.log('wat.content', wat.content)
console.log(wat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment