Skip to content

Commit

Permalink
Greatly simplify code
Browse files Browse the repository at this point in the history
Credit to @jamestalmage for the idea
  • Loading branch information
ariporad committed Dec 25, 2015
1 parent 5360389 commit 2b10bdb
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 27 deletions.
58 changes: 33 additions & 25 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,38 @@
'use strict';
module.exports = function (ms) {
ms = ms || 0;

var promise = new Promise(function (resolve) {
setTimeout(resolve, ms);
});

function thunk(result) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(result);
}, ms);
});
}
module.exports = generate(true);
module.exports.resolve = module.exports;
module.exports.reject = generate(false);

function generate(shouldResolve) {
return function (ms, value) {
ms = ms || 0;

thunk.then = promise.then.bind(promise);
thunk.catch = promise.catch.bind(promise);
function pickAction(resolve, reject) {
var action = shouldResolve ? resolve : reject;
if (arguments.length > 1) {
action = action.bind(null, value);
}

return thunk;
};
return action;
}

module.exports.reject = function (ms, value) {
if (arguments.length > 1) {
return new Promise(function (resolve, reject) {
setTimeout(reject.bind(null, value), ms);
var promise = new Promise(function (resolve, reject) {
setTimeout(pickAction(resolve, reject), ms);
});
}
return module.exports.reject.bind(null, ms);
};

function thunk(result) {
promise.catch(noop);
value = value || result;
return new Promise(function (resolve, reject) {
setTimeout(pickAction(resolve, reject), ms);
});
}

thunk.then = promise.then.bind(promise);
thunk.catch = promise.catch.bind(promise);

return thunk;
};
}

function noop() {}
12 changes: 10 additions & 2 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,12 @@ import inRange from 'in-range';
import fn from './';

test('promise', async t => {
t.plan(1);
const end = timeSpan();
await fn(50);
t.true(inRange(end(), 30, 70), 'is delayed');
});

test('thunk', async t => {
t.plan(2);
const end = timeSpan();
const result = await Promise.resolve('foo').then(fn(50));
t.true(inRange(end(), 30, 70), 'is delayed');
Expand All @@ -24,6 +22,16 @@ test('.reject() with two arguments', async t => {
t.true(inRange(end(), 30, 70), 'is delayed');
});

test('.reject() with two arguments (as a thunk)', async t => {
const end = timeSpan();
await t.throws(
Promise.resolve('foo').then(fn.reject(50, new Error('bar'))),
'bar',
'promise is rejected with the resolution value'
);
t.true(inRange(end(), 30, 70), 'is delayed');
});

test('.reject() with one argument (thunk)', async t => {
const end = timeSpan();
await t.throws(
Expand Down

0 comments on commit 2b10bdb

Please sign in to comment.