0.1.1 • Published 5 years ago

loop-breaker v0.1.1

Weekly downloads
11
License
MIT
Repository
-
Last release
5 years ago

loop-breaker

A simple library that transforms JavaScript code to prevent loops from running infinitely.

loop-breaker has the same goals as, and takes inspiration from, loop-protect. However, while loop-protect uses regular expressions to transform loops (smaller library size, less accurate), loop-breaker uses an AST transform (bigger library, reliably accurate).

Installation

loop-protect can be installed via npm/yarn:

$ npm install loop-protect

or

$ yarn add loop-protect

Or as a standalone script in the browser:

<script src="/js/loopBreaker.min.js"></script>

Usage

import loopBreaker from 'loop-breaker';

const source = 'const myCode = "hello world";';
const result = loopBreaker(source, {
  sourceFileName: 'mySource.js', // Optional. Defaults to loopBreaker.js
});

const transformedCode = result.code;
const sourceMap = result.map;

How it works

Modifies input code to do the following:

  • Adds a top-level function __loopBreaker which checks whether the currently executing loop should be broken
  • Injects into for, while, and do-while loops a call to loopBreaker()

The loop is considered likely-infinite if the following two conditions hold:

  • The loop has executed at least ten thousand times
  • The loop has been running for at least one second of wall time

So, with the original input code:

for (var i = 0; i < 1000000; i--) {
  console.log(i);
}

Will look like this:

var __loopBreaker = (function() {
  var count = 0;
  var startTime;
  return function() {
    startTime || (startTime = Date.now());
    count += 1;
    if (count > 10000 && (Date.now() - startTime > 1000)) {
      throw new Error("Loop Broken!");
    }
  };
}());
for (var i = 0; i < 1000000; i--) {
  __loopBreaker();
  console.log(i);
}
0.1.1

5 years ago

0.1.1-alpha.1

6 years ago

0.1.0

6 years ago

0.1.0-alpha.8

7 years ago

0.1.0-alpha.7

7 years ago

0.1.0-alpha.6

7 years ago