Skip to content

Instantly share code, notes, and snippets.

@imsaravana369
Last active May 27, 2023 07:21
Show Gist options
  • Save imsaravana369/a4a0340249125fcdb12d9caf1a53869f to your computer and use it in GitHub Desktop.
Save imsaravana369/a4a0340249125fcdb12d9caf1a53869f to your computer and use it in GitHub Desktop.
// 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