Skip to content

Instantly share code, notes, and snippets.

@yamad
Created July 4, 2018 00:18
Show Gist options
  • Save yamad/2df804f7ab086f71b7e1b6260134e71a to your computer and use it in GitHub Desktop.
Save yamad/2df804f7ab086f71b7e1b6260134e71a to your computer and use it in GitHub Desktop.
sql-style joins using key decoration in javascript
function mergeData(...arrs) {
const getKey = el => el.affId + ',' + el.offId
const full = concat(arrs)
const groupedObj = groupBy(full, getKey)
const grouped = Object.values(groupedObj)
const merged = grouped.map(mergeObjects)
return merged
}
function concat(arrs) {
const cat = (a, b) => [...a, ...b]
return arrs.reduce(cat, [])
}
function groupBy(arr, keyfunc) {
let res = {}
for (el of arr) {
let key = keyfunc(el)
if (res[key])
res[key].push(el)
else
res[key] = [el]
}
return res
}
function mergeObjects(arr) {
const assign = (acc, el) => Object.assign(acc, el)
return arr.reduce(assign, {})
}
function example() {
const netArr = [
{affId: '1', offId: '200', revenue: '12'},
{affId: '2', offId: '201', revenue: '3'},
{affId: '3', offId: '202'}
]
const tuneArr = [
{affId: '1', offId: '200', revenue: '12'},
{affId: '2', offId: '201', revenue: '3'},
{affId: '3', offId: '202'}
]
const tabArr = [
{affId: '1', cost: '4', clicks: '5',
actions: '10', cost: '.5', offId: '200'},
{affId: '2', cost: '2', clicks: '5',
actions: '30', cost: '50.0', offId: '201'},
{affId: '3', cost: '5', clicks: '8',
actions: '310', cost: '1.5', offId: '202'}
]
return mergeData(netArr, tuneArr, tabArr)
}
module.exports = {
mergeData,
example
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment