Skip to content

Instantly share code, notes, and snippets.

@jon49
Last active September 23, 2015 17:48
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 jon49/8dbe86251c425ee38f16 to your computer and use it in GitHub Desktop.
Save jon49/8dbe86251c425ee38f16 to your computer and use it in GitHub Desktop.
object transform
const objectTransform = r.curry(function OT_(template, obj) {
let originalObject = obj
function OT(template, obj) {
let o = obj
const
t = template,
keys = r.keys(template)
const
result = r.reduce((acc, key: string) => {
const mapT = t[key], val = <any> r.path([key], o)
let num = void 0
if (key === '>>0') {
console.log()
}
const result = (
r.isNil(val) && key.indexOf('>') !== 0
? acc
: r.is(Boolean, mapT)
? mapT === true
? r.assoc(key, val, acc)
: acc
: r.is(String, mapT)
? r.assoc(mapT, val, acc)
: r.is(Function, mapT)
? key === '>'
? mapT(o, key, originalObject, acc)
: (num = r.path([1], key.match(/>>(\d)/)))
? num === '0'
? (o = r.merge(o, mapT(o, key, originalObject, acc)), acc)
: num === '2'
? (originalObject = r.merge(originalObject, mapT(o, key, originalObject, acc)), acc)
: r.merge(acc, mapT(o, key, originalObject, acc))
: r.assoc(key, mapT(o, key, originalObject, acc), acc)
: r.is(Array, mapT)
? mapT.length === 1
? r.assoc(key, map(OT.bind(null, mapT[0]), val), acc)
: r.assoc(key, map(r.apply(OT), r.zip(mapT, val)), acc)
: r.is(Object, mapT)
? r.assoc(key, OT(mapT, val), acc)
: acc)
return result
}, {}, keys)
return result
}
const finalResult = OT(template, obj)
return finalResult
})
// Example usage
exampleViewMap = objectTransform({
box: true,
dueDate: true,
dealer: true,
emailPercentages: (o, key) => Math.round(o[key]) + '%',
gross: true,
//call a generic view that maps over an object.
'>': (x, y, z, result) => objectView(result)
}),
serviceDealerViewMap = objectTransform({
note: true,
startingContractNumber: true,
endingContractNumber: true,
manualContractsCompleted: true,
coursesCompleted: true,
courseList: [{
'>': o => ({ name: `${o.firstName} ${o.lastName}` }),
courses: true,
}],
feedback: true,
// call a reusable view that maps over the feedback object and is generic for the rest of the keys
// I could have a function here that just says `fourth(feedback)` instead
'>': (x, y, z, acc) => feedback(acc)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment