nth.js 824 B

12345678910111213141516171819202122232425262728293031
  1. /**
  2. * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. /**
  6. * @module utils/nth
  7. */
  8. /**
  9. * Returns `nth` (starts from `0` of course) item of the given `iterable`.
  10. *
  11. * If the iterable is a generator, then it consumes **all its items**.
  12. * If it's a normal iterator, then it consumes **all items up to the given index**.
  13. * Refer to the [Iterators and Generators](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Iterators_and_Generators)
  14. * guide to learn differences between these interfaces.
  15. *
  16. * @param {Number} index
  17. * @param {Iterable.<*>} iterable
  18. * @returns {*}
  19. */
  20. export default function nth( index, iterable ) {
  21. for ( const item of iterable ) {
  22. if ( index === 0 ) {
  23. return item;
  24. }
  25. index -= 1;
  26. }
  27. return null;
  28. }