Skip to content

Instantly share code, notes, and snippets.

@tjcelaya
Last active January 23, 2016 08:41
Show Gist options
  • Save tjcelaya/d9c71e8bfe1bb177effb to your computer and use it in GitHub Desktop.
Save tjcelaya/d9c71e8bfe1bb177effb to your computer and use it in GitHub Desktop.
lodash-fp list of objects self-join
////
// WARNING: THE FOLLOWING IS ONLY A TEST OF THE EMERGENCY IN-MEMORY ORM
// NO CLAIMS ARE MADE AS TO THE PRACTICALITY OR WEB-SCALE-NESS OF PERFORMING CLIENT-SIDE JOINS
////
let l = require('lodash-fp')
l.mixin({ id: l.identity })
l.mixin({ prop: l.property })
os = [
{ id: 1, title: 'test1', other_id: [ 3, 2, 5 ] },
{ id: 2, title: 'test2', other_id: [ ] },
{ id: 3, title: 'test3', other_id: [ 2 ] },
{ id: 4, title: 'test4', other_id: [ 3, 2 ] },
{ id: 5, title: 'test5', other_id: [ 1, 2, 4 ] }
]
// copy, updates won't be visible inside the dupes
l.mixin({ set: (o, k, v) => l.assign(o || {}, { [k]: v }) })
// set by ref
l.mixin({ setmut: (o, k, v) => { o[k] = v; return o }})
// join by reference
let joined_os = l.map((o) => // attach to each o
l.setmut(o,
'others', // on the o.other prop
l.indexBy( // an index created from
'id', // the id prop
l.filter( // from the list of o which
l.flow( //
l.prop('id'), // have an id prop
l.partialRight(l.includes, o.other_id) // included in that o's list of related models
), //
os) //
) //
) //
)(os) //
let indexed_os = l.indexBy('id', joined_os)
// =>
// { '1':
// { id: 1,
// title: 'test1',
// other_id: [ 3, 2, 5 ],
// others: { '2': [Object], '3': [Object], '5': [Object] } },
// '2': { id: 2, title: 'test2', other_id: [], others: {} },
// '3':
// { id: 3,
// title: 'test3',
// other_id: [ 2 ],
// others: { '2': [Object] } },
// '4':
// { id: 4,
// title: 'test4',
// other_id: [ 3, 2 ],
// others: { '2': [Object], '3': [Object] } },
// '5':
// { id: 5,
// title: 'test5',
// other_id: [ 1, 2, 4 ],
// others: { '1': [Object], '2': [Object], '4': [Object] } } }
// the following will only work with setmut, set would makes a copy
indexed_os[1]['others'][5]['others'][1] === indexed_os[1]
// => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment