Skip to content

Instantly share code, notes, and snippets.

@fetchTe
Created May 1, 2016 01:43
Show Gist options
  • Save fetchTe/c13ef537a5359d9cbc3d69aee47624e6 to your computer and use it in GitHub Desktop.
Save fetchTe/c13ef537a5359d9cbc3d69aee47624e6 to your computer and use it in GitHub Desktop.
kolme response

Function: a bunch of code you can call. It can take any number of parameters, and it can have a name.

Closure: The context, or variables and their values around the function when it was defined.

Generator: a special function that can yield more than one result when called in a loop. Generator functions also have closures.

So to shortly answer to your question: functions can't do anything a generator cannot do; or, generators can do more. And they all have closures.

Here's a simple example to understand closures:

/**
 * Returns a function which adds the given base.
 */
function getAddFunction(base) {
    return function(number) {
        // The right base is kept in this function closure
        return base + number;
    }
}

// We get two times the same function, just with different closures
var add2 = getAddFunction(2); // a function with base = 2
var add3 = getAddFunction(3); // a function with base = 3

// 2 + 1, 3 + 1
console.log(add2(1), add3(1));

Now here's a simple generator which I like a lot, and stole from python:

/**
 * Yields a series of numbers, from min up to max (max not included), with
 * the given step.
 */
function* range(max, min = 0, step = 1) {
    for (let i = min; i < max; i += step) {
        yield i;
    }
}

// Prints numbers from 0 to 9
for (let i of range(10)) {
    console.log(i);
}
// Getting a range as an array:
console.log(Array.from(range(10));

And finally, a combination of all the things: a generator function sporting closures:

/**
 * Returns a generator function which will yield multiples of the given
 * number
 */
function getSerieGenerator(step) {
    return function*(max, min = 0) {
        for (let i = min; i < max; i+= base) {
            yield i;
        }
    }
}

// Two identical generators with different contexts
let pairNumbers = getSerieGenerator(2);
let threeMultiples = getSerieGenerator(3);

// Prints all pair numbers up to 10
console.log(Array.from(pairNumbers(10)));

// Prints all three multiples up to 10
console.log(Array.from(threeMultiples(10)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment