split.js 804 B

1234567891011121314151617181920212223242526272829303132333435
  1. /**
  2. * Split array into a fixed number of segments.
  3. */
  4. function split(array, segments) {
  5. segments = segments || 2;
  6. var results = [];
  7. if (array == null) {
  8. return results;
  9. }
  10. var minLength = Math.floor(array.length / segments),
  11. remainder = array.length % segments,
  12. i = 0,
  13. len = array.length,
  14. segmentIndex = 0,
  15. segmentLength;
  16. while (i < len) {
  17. segmentLength = minLength;
  18. if (segmentIndex < remainder) {
  19. segmentLength++;
  20. }
  21. results.push(array.slice(i, i + segmentLength));
  22. segmentIndex++;
  23. i += segmentLength;
  24. }
  25. return results;
  26. }
  27. module.exports = split;