Functional Programming With Javascript: Generator, Lazy functions

Generator

function* generator() {
console.log('one');
yield 1;

console.log('two');
yield 2;
console.log('three');
yield 3; console.log('four');}const iterable = generator();console.log(iterable);
console.log(iterable.next());
console.log(iterable.next());
console.log(iterable.next());
console.log(iterable.next());
----------------------------- Console -----------------------------Object [Generator] {}
one
{ value: 1, done: false }
two
{ value: 2, done: false }
three
{ value: 3, done: false }
four
{ value: undefined, done: true }
Normal functions
Lazy functions

Lazy functions

function *map(collection, mapper) {  for (const value of collection) {    yield mapper(value);  }}module.exports = map;
test('map', () => {  const squared = map([1, 2, 3, 4, 5], (value) => {    console.log(value);    return value * value;  });  expect(squared.next().value).toBe(1);
expect(squared.next().value).toBe(4);
});----------------------------- Console -----------------------------
1
2
function* filter(collection, predicate) {  for (const value of collection) {    if (predicate(value)) {      yield value;    }  }}module.exports = filter;
test('filter', () => {  let called = 0;  const odds = filter([1, 2, 3, 4, 5], (value) => {    called++;    return value % 2;  });  expect(odds.next().value).toBe(1);  expect(odds.next().value).toBe(3);  expect(called).toBe(3);});

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store