Skip to content

Commit

Permalink
Internal tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Nov 9, 2023
1 parent dfc2e4a commit b2dd418
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
13 changes: 6 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import vm from 'node:vm';

export default function functionTimeout(function_, {timeout} = {}) {
const script = new vm.Script('returnValue = function_()');
const script = new vm.Script('returnValue = functionToRun()');

const wrappedFunction = (...arguments_) => {
const context = {
function_: () => function_(...arguments_),
};
// TODO: Document the `context` option and add to types when I know it's something I want to keep.

// If you use the `context` option, you do it at your own risk.
export default function functionTimeout(function_, {timeout, context = vm.createContext()} = {}) {
const wrappedFunction = (...arguments_) => {
context.functionToRun = () => function_(...arguments_);
script.runInNewContext(context, {timeout});

return context.returnValue;
};

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"node": "./index.js",
"default": "./browser.js"
},
"sideEffects": false,
"engines": {
"node": ">=18"
},
Expand Down
8 changes: 8 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,11 @@ test('no timeout', t => {
const fixtureFunction = (a, b) => [a, b];
t.deepEqual(functionTimeout(fixtureFunction)(1, 2), [1, 2]);
});

test('multiple', t => {
const run = functionTimeout((a, b) => [a, b], {timeout: 100});
t.deepEqual(run(1, 2), [1, 2]);
t.deepEqual(run(1, 3), [1, 3]);
t.deepEqual(run(1, 4), [1, 4]);
t.deepEqual(run(1, 5), [1, 5]);
});

0 comments on commit b2dd418

Please sign in to comment.