Last active
May 27, 2023 07:21
-
-
Save imsaravana369/a4a0340249125fcdb12d9caf1a53869f to your computer and use it in GitHub Desktop.
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
// Just a simple example to understand how JS object is decoded to purescript record. | |
// Skipping unwrapSingleArguments, unwrapSingleConstructors, sumEncoding. | |
purescript_obj = { "firstName" : "Saravana", "lastName" : "Murugesan"} | |
foreign_obj = { "first_name" : "Saravana", "last_name" : "Murugesan"} | |
const camelToSnakeCase = str => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`); | |
function decode(foreign_obj , res,options){ | |
if (typeof res === 'object'){ // just a generalization | |
decodeRecord(foreign_obj,res,options); | |
}else{ | |
// encode primitves | |
// Considering them as same | |
} | |
return res; | |
} | |
function decodeRecord(foreign_obj,res,options){ | |
// assume you know `purescript_obj` keys here | |
Object.keys(purescript_obj).forEach(ps_key => { | |
let js_key = options.fieldTransform(ps_key); | |
if(foreign_obj.hasOwnProperty(js_key)){ | |
let js_val = foreign_obj[js_key]; | |
delete foreign_obj[js_key]; | |
res[ps_key] = decode(foreign_obj,js_val,options); | |
}else{ | |
// if type is `Maybe` we can set the value as Nothing | |
throw new Error(`Error At Property ${ps_key}` ); | |
} | |
}); | |
} | |
// program starts here | |
res = {} | |
options = {fieldTransform : camelToSnakeCase} | |
decode(foreign_obj,res,options) | |
console.log(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment