Created
October 13, 2019 12:41
-
-
Save alinz/95abf4ea6a218d1b48fad327999d400b to your computer and use it in GitHub Desktop.
Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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