Skip to content

Instantly share code, notes, and snippets.

@alinz
Created October 13, 2019 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alinz/95abf4ea6a218d1b48fad327999d400b to your computer and use it in GitHub Desktop.
Save alinz/95abf4ea6a218d1b48fad327999d400b to your computer and use it in GitHub Desktop.
Model
export class Model {
constructor(obj: any) {
for (let key in obj) {
this.unmarshal(toCamelCase(key), obj[key])
}
}
marshal(): any {
return Object.keys(this).reduce((obj: any, key: string) => {
obj[toSnakeCase(key)] = toJS(this[key])
return obj
}, {})
}
unmarshal(filed: string, value: any) {
throw new Error('unmarshal is not implemented')
}
}
export const toSnakeCase = (str: string) => {
if (!str) return ''
return str
.replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g, '')
.replace(/([a-z])([A-Z])/g, (m, a, b) => a + '_' + b.toLowerCase())
.replace(/[^A-Za-z0-9]+|_+/g, '_')
.toLowerCase()
}
export const toCamelCase = (s: string) => {
return s
.replace(/_/g, ' ')
.replace(/\s(.)/g, (v) => v.toUpperCase())
.replace(/\s/g, '')
.replace(/^(.)/, (v) => v.toLowerCase())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment