Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
hut36 committed Oct 12, 2023
0 parents commit 0db6240
Show file tree
Hide file tree
Showing 9 changed files with 3,024 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist
node_modules
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
The MIT License (MIT)

Copyright (c) 2023 Tao Hu

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
87 changes: 87 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# serq - execute functions serially

This project is inspired by [seq-queue](https://github.com/changchang/seq-queue).

## USAGE

### BASICS

```js
let queue = new Serq()

queue.push(async () => {
await new Promise(r => { setTimeout(r, 100) })
console.log('func 0')
})

queue.push(() => {
console.log('func 1')
})

// output:
//
// func 0
// func 1
```

#### Return values

```js
let queue = new Serq()
let ret = queue.push(() => {
return 'value'
})

console.log(await ret)

// output:
//
// value
```

#### Errors

```js
let queue = new Serq()
queue.push(() => {
throw new Error('an error')
})
.catch(err) {
console.log('error: ', err.message)
}

// output:
//
// an error
```

#### Timeouts

When timeout happens, Serq executes the function next in queue.

```js
let queue = new Serq(500) // default timeout is 3000

queue.push(async () => {
await new Promise(r => { setTimeout(r, 1000) })
console.log('task 0 done')
}, {
ontimeout: () => {
console.log('timeout')
}
})

queue.push(() => {
console.log('task 1 done')
})

// output:
//
// timeout
// task 1 done
// task 0 done
```

## LICENSE

MIT
72 changes: 72 additions & 0 deletions karma.conf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Karma configuration
// Generated on Thu Apr 13 2023 15:07:58 GMT+0800 (China Standard Time)

const webpackConfig = require('./webpack.config.js');

module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',

// frameworks to use
// available frameworks: https://www.npmjs.com/search?q=keywords:karma-adapter
frameworks: ['mocha'],

plugins: [
require('karma-webpack'),
require('karma-mocha'),
require('karma-mocha-reporter'),
require('karma-chrome-launcher'),
require('karma-firefox-launcher'),
require('karma-safari-launcher'),
require('mochapack'),
],

// list of files / patterns to load in the browser
files: [
{ pattern: 'src/**/*.js', watched: true, included: false, served: false },
{ pattern: 'tests/**/*.js', watched: false },
],

// list of files / patterns to exclude
exclude: [],

// preprocess matching files before serving them to the browser
// available preprocessors: https://www.npmjs.com/search?q=keywords:karma-preprocessor
preprocessors: {
'tests/**/*.js': ['webpack'],
},

webpack: webpackConfig,

// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://www.npmjs.com/search?q=keywords:karma-reporter
reporters: ['mocha'],

// web server port
port: 9876,

// enable / disable colors in the output (reporters and logs)
colors: true,

// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,

// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,

// start these browsers
// available browser launchers: https://www.npmjs.com/search?q=keywords:karma-launcher
browsers: ['ChromiumHeadless', 'Safari', 'FirefoxHeadless'],

// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,

// Concurrency level
// how many browser instances should be started simultaneously
concurrency: Infinity
})
}
33 changes: 33 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "serq",
"version": "0.1.0",
"description": "Serial queue.",
"keywords": [
"queue",
"serial"
],
"author": "Tao Hu <[email protected]>",
"main": "src/index.js",
"devDependencies": {
"chai": "^4.3.10",
"karma": "^6.4.2",
"karma-chrome-launcher": "^3.2.0",
"karma-firefox-launcher": "~2.1.2",
"karma-mocha": "^2.0.1",
"karma-mocha-reporter": "^2.2.5",
"karma-safari-launcher": "~1.0.0",
"karma-webpack": "^5.0.0",
"mocha": "^10.2.0",
"mochapack": "^2.1.4",
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4"
},
"dependencies": {
"promise-deferred": "^2.0.4"
},
"scripts": {
"build": "NODE_ENV=production webpack --progress",
"test": "karma start karma.conf.js"
},
"license": "MIT"
}
112 changes: 112 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
// Copyright (c) 2023 Tao Hu.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

import Deferred from 'promise-deferred';

let DEFAULT_TIMEOUT = 3000;

class Serq {
static STATUS_IDLE = 0
static STATUS_BUSY = 1
static STATUS_CLOSED = 2

constructor(timeout = DEFAULT_TIMEOUT) {
this.id = 0
this.timeout = timeout
this.status = Serq.STATUS_IDLE;
this.queue = [];
this.pp = Promise.resolve()
}

push(fn, options) {
if (this.status !== Serq.STATUS_IDLE && this.status !== Serq.STATUS_BUSY) {
throw new Error(`push(): Invalid status: ${this.status}.`);
}

if (typeof fn !== 'function') {
throw new Error('fn should be a function.');
}

let defer = Deferred()
let ondone = ret => { defer.resolve(ret) }
let onerror = error => { defer.reject(error) }

this.queue.push({ fn: fn, ondone: ondone, onerror: onerror, ontimeout: options ? options.ontimeout : undefined });

if (this.status === Serq.STATUS_IDLE) {
this.status = Serq.STATUS_BUSY;
let self = this;
this.pp = this.pp.then(function() { self._next(self.id); })
}

return defer.promise;
}

close() {
if (this.status !== Serq.STATUS_IDLE && this.status !== Serq.STATUS_BUSY) {
return;
}

this.status = Serq.STATUS_CLOSED;
}

_next(id) {
if (this.id !== id) {
return
}
if (this.status !== Serq.STATUS_BUSY && this.status !== Serq.STATUS_CLOSED) {
return
}

if (this.timer) {
clearTimeout(this.timer);
this.timer = undefined;
}

let task = this.queue.shift();
if (!task) {
if (this.status === Serq.STATUS_BUSY) {
this.status = Serq.STATUS_IDLE;
}
return;
}

let self = this;
task.id = ++this.id

this.timer = setTimeout(function() {
self.pp = Promise.resolve().then(() => { self._next(task.id); })
typeof (task.ontimeout) === 'function' && task.ontimeout()
}, this.timeout);

this.pp = this.pp
.then(task.fn)
.catch(error => {
typeof task.onerror === 'function' && Promise.resolve().then(() => { task.onerror(error) })
})
.then(ret => { typeof task.ondone === 'function' && Promise.resolve().then(() => { task.ondone(ret) }) })
.then(() => { self._next(task.id); })
}
}

export default Serq
Loading

0 comments on commit 0db6240

Please sign in to comment.