Skip to content

Instantly share code, notes, and snippets.

@resistdesign
Created November 15, 2016 20:43
Show Gist options
  • Save resistdesign/28baccfc18bf4acc32b14d25ebb589c6 to your computer and use it in GitHub Desktop.
Save resistdesign/28baccfc18bf4acc32b14d25ebb589c6 to your computer and use it in GitHub Desktop.
Collate Pages
function collate(pages = []){
const flats = [];
const { length } = pages;
const flatLength = Math.ceil(length/2);
const even = length % 2 === 0;
const newPages = [...pages];
if(!even){
const lastPage = newPages.pop();
newPages.push(undefined);
newPages.push(lastPage);
}
for(let i = 0; i < flatLength; i++){
const evenFlat = i % 2 === 0;
if(!evenFlat){
flats.push([
newPages[i],
newPages[(newPages.length - 1) - (i)]
]);
}else{
flats.push([
newPages[(newPages.length - 1) - (i)],
newPages[i]
]);
}
}
return flats;
}
const booklet = collate([
1, 2, 3, 4, 5, 6, 7, 8, 9
]);
console.log(booklet);
@resistdesign
Copy link
Author

Output:

[
  [
    9,
    1
  ],
  [
    2,
    undefined
  ],
  [
    8,
    3
  ],
  [
    4,
    7
  ],
  [
    6,
    5
  ]
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment