Skip to content

Commit

Permalink
Add a concise generator method.
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Mar 3, 2015
1 parent f77c0cd commit ea86f3d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@
[![browser support][testling-svg]][testling-url]

Returns an arbitrary generator function, or undefined if generator syntax is unsupported.
If both generator syntax and concise method syntax are supported, the generator function returned will have a "concise" property containing a concise generator method.

## Example
```js
var maybeGeneratorFunction = require('make-generator-function');
if (maybeGeneratorFunction) {
assert(typeof maybeGeneratorFunction === 'function');
var maybeConciseGeneratorMethod = maybeGeneratorFunction.concise;
if (maybeConciseGeneratorMethod) {
assert(typeof maybeConciseGeneratorMethod === 'function');
}
} else {
assert(typeof maybeGeneratorFunction === 'undefined');
}
Expand Down
10 changes: 8 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@
var makeGeneratorFunction = function () {
return Function('return function* () { var x = yield; return x || 42; }')();
};
var makeConciseGeneratorMethod = function () {
return Function('return { * gen( ){ } }.gen;')();
};
var generatorFunc;
try { generatorFunc = makeGeneratorFunction(); } catch (e) {}
if (generatorFunc) {
try {
generatorFunc.concise = makeConciseGeneratorMethod();
} catch (e) {}
}

module.exports = generatorFunc;


11 changes: 11 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@ var genFunction = require('../');
test('generators supported', { skip: !genFunction }, function (t) {
t.equal(typeof genFunction, 'function', 'genFunction is function');
t.equal(String(genFunction), 'function* () { var x = yield; return x || 42; }', 'genFunction has expected body');

t.test('concise methods supported', { skip: !genFunction.concise }, function (st) {
t.equal(typeof genFunction.concise, 'function', 'genFunction.concise is function');
st.end();
});

t.test('concise methods not supported', { skip: genFunction.concise }, function (st) {
t.equal(typeof genFunction.concise, 'undefined', 'genFunction.concise is undefined');
st.end();
});

t.end();
});

Expand Down

0 comments on commit ea86f3d

Please sign in to comment.