Skip to content

Instantly share code, notes, and snippets.

@Gioni06
Last active August 13, 2021 15:04
Show Gist options
  • Select an option

  • Save Gioni06/e9c6c8be356128fcb74ec0e1634a5b25 to your computer and use it in GitHub Desktop.

Select an option

Save Gioni06/e9c6c8be356128fcb74ec0e1634a5b25 to your computer and use it in GitHub Desktop.
Fun with Arrays
const sourceA = [
[
...[...Array(5).keys()].map((value) => {
return { ref: 'sourceA', value }
}),
],
[
...[...Array(13).keys()].map((value) => {
return { ref: 'sourceB', value }
}),
],
[
...[...Array(22).keys()].map((value) => {
return { ref: 'sourceC', value }
}),
],
]
const sourceB = [
[
...[...Array(5).keys()].map((value) => {
return { ref: 'sourceA', value }
}),
],
[
...[...Array(5).keys()].map((value) => {
return { ref: 'sourceB', value }
}),
],
[
...[...Array(5).keys()].map((value) => {
return { ref: 'sourceC', value }
}),
],
]
const sourceC = [
[
...[...Array(1).keys()].map((value) => {
return { ref: 'sourceA', value }
}),
],
[
...[...Array(0).keys()].map((value) => {
return { ref: 'sourceB', value }
}),
],
[
...[...Array(100).keys()].map((value) => {
return { ref: 'sourceC', value }
}),
],
]
const roundRobinWithBreakAtDesiredLength = (arr, results, targetLength) => {
if (arr.length === 0) return results
const newResults = arr.reduce(
(acc, current) => {
if (current.length > 0 && acc.results.length < targetLength) {
acc.results.push(current.shift())
acc.arr.push(current)
}
return acc
},
{ arr: [], results }
)
return roundRobinWithBreakAtDesiredLength(
newResults.arr,
newResults.results,
targetLength
)
}
function doStuff(source, targetLength) {
const result = []
const s = JSON.parse(JSON.stringify(source)) // poor mans deep clone
return roundRobinWithBreakAtDesiredLength(s, result, targetLength)
}
console.log(doStuff(sourceA, 20))
console.log(doStuff(sourceA, 20).length)
console.log(doStuff(sourceB, 20))
console.log(doStuff(sourceB, 20).length)
console.log(doStuff(sourceC, 20))
console.log(doStuff(sourceC, 20).length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment