Skip to content

Instantly share code, notes, and snippets.

@jmakeig
Created April 10, 2019 19:41
Show Gist options
  • Save jmakeig/83f6903ad4f40e48cdc59550e436c3d6 to your computer and use it in GitHub Desktop.
Save jmakeig/83f6903ad4f40e48cdc59550e436c3d6 to your computer and use it in GitHub Desktop.
takeWhile implementation for JavaScript Iterables
function* takeWhile(iterable /* Sequence, Array, etc. */, predicate = () => true) {
// TODO: Test that iterable is, well, iterable and not something else
for (const item of iterable) {
if (predicate(item)) {
yield item;
} else {
break;
}
}
}
console.log(Array.from(takeWhile([1, 2, 3, 4, 5, 6, 7], x => x < 3)));
@jmakeig
Copy link
Author

jmakeig commented May 7, 2019

Add index param so that a predicate can use it to determine whether to take. For example, I only want the first 20.

function* takeWhile(iterable /* Sequence, Array, etc. */, predicate = () => true) {
  // TODO: Test that iterable is, well, iterable and not something else
  let index = 0;
  for (const item of iterable) {
    if (predicate(item, index++, iterable)) {
      yield item;
    } else {
      break;
    }
  }
}

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