back to basics

This commit is contained in:
Michael Barrett 2016-01-15 10:00:12 +00:00
parent ca1e42925e
commit 8c0926f588
19 changed files with 127 additions and 522 deletions

View File

@ -2,6 +2,4 @@ languages:
JavaScript: true JavaScript: true
exclude_paths: exclude_paths:
- Gulpfile.js - test.js
- test/*
- dist/*

3
.gitignore vendored
View File

@ -1,2 +1 @@
/node_modules/ node_modules
/build/

View File

@ -1,4 +1,4 @@
{ {
"preset": "jquery", "preset": "node-style-guide",
"esnext": true "requireCapitalizedComments": false
} }

View File

@ -1,3 +1 @@
{ {}
"esnext": true
}

View File

@ -1,2 +1,2 @@
/* /*
!/dist/ !/index.js

View File

@ -17,7 +17,9 @@ env:
global: global:
- secure: dILRjgEPjnDy8wcqSkKS4KoxSykeffpReeiRXcXNK9iJvoxNQpfEycVuC7eG4KmdHdLj8RmrPIHE3S2x+su7LD5Nly/StaxfYTWIi1++3wSLP+SlDdv9h+uy2uA6bMsP4hys2ArQ+i/P5V4r5zq1iLIf3mavIchNwTT3ThhOIso= - secure: dILRjgEPjnDy8wcqSkKS4KoxSykeffpReeiRXcXNK9iJvoxNQpfEycVuC7eG4KmdHdLj8RmrPIHE3S2x+su7LD5Nly/StaxfYTWIi1++3wSLP+SlDdv9h+uy2uA6bMsP4hys2ArQ+i/P5V4r5zq1iLIf3mavIchNwTT3ThhOIso=
script: gulp ci script:
- npm test
- npm run sa
after_script: after_script:
- istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec - istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec

View File

@ -1,5 +1,7 @@
#Changelog #Changelog
## 2.0.0
##1.1.1 ##1.1.1
- src now uses ES6 - src now uses ES6

View File

@ -1,12 +1,12 @@
#Contributing # Contributing
Contributions are **welcome** and will be fully **credited**. Contributions are **welcome** and will be fully **credited**.
Contributions can be made via a Pull Request on [Github](https://github.com/mike182uk/timestring). Contributions can be made via a Pull Request on [Github](https://github.com/mike182uk/timestring).
##Pull Requests ## Pull Requests
- **[jQuery coding style](https://contribute.jquery.org/style-guide/js/)** - [JSCS](http://jscs.info/). Make sure you run `gulp sa` before committing your code. - **[Node coding style](https://github.com/felixge/node-style-guide)** - [JSCS](http://jscs.info/). Make sure you run `npm run sa` before committing your code.
- **Add tests where appropriate** - [Mocha](http://mochajs.org/), [Chai](http://chaijs.com/) - **Add tests where appropriate** - [Mocha](http://mochajs.org/), [Chai](http://chaijs.com/)
@ -18,30 +18,8 @@ Contributions can be made via a Pull Request on [Github](https://github.com/mike
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting. - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting.
##Building The Project ## Running Tests
[Gulp](http://gulpjs.com/) is used to build the project. The project uses ES6 so it needs to be transpiled. Once transpiled the code is then [browserified](http://browserify.org/). You can build the project by running:
```bash ```bash
gulp build npm test
``` ```
This will perform all build steps, including running the tests and static analysis tools.
##Running Tests
Once the project has been built, the tests can be run with:
```bash
gulp test
```
Alternatively, to build and test at the same time you can run:
```bash
gulp ci
```
This will transpile, browserify and run the tests and static analysis tools.

View File

@ -1,91 +0,0 @@
var gulp = require('gulp');
var $ = require('gulp-load-plugins')({
scope: 'devDependencies'
});
var browserify = require('browserify');
var del = require('del');
var runSequence = require('run-sequence');
var source = require('vinyl-source-stream');
gulp.task('static-analysis:lint', function () {
gulp.src('./src/**/*.js')
.pipe($.jshint('.jshintrc'))
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('static-analysis:cs', function () {
return gulp.src('./src/**/*.js')
.pipe($.jscs());
});
gulp.task('test', function () {
return gulp.src('./test/timestring.js', { read: false })
.pipe($.mocha());
});
gulp.task('build:clean', function (callback) {
del(['./build/**/*'], callback);
});
gulp.task('build:transpile', function () {
return gulp.src(['./src/Timestring.js', './src/String.parseTime.js'])
.pipe($.sourcemaps.init())
.pipe($.concat('timestring.js'))
.pipe($.babel())
.pipe($.sourcemaps.write())
.pipe(gulp.dest('./build'));
});
gulp.task('build:lib', function () {
return gulp.src('./build/timestring.js')
.pipe(gulp.dest('./dist/lib'));
});
gulp.task('build:browserify', function() {
return browserify('./build/timestring.js', { standalone: 'Timestring', debug: true })
.bundle()
.on('error', function(e){
console.log(e.message);
this.emit('end');
})
.pipe(source('timestring.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('build:minify', function () {
return gulp.src('./dist/timestring.js')
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.uglify())
.pipe($.rename({
extname: '.min.js'
}))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('dist'));
});
gulp.task('build', function (callback) {
runSequence(
['static-analysis:lint', 'static-analysis:cs'],
'build:clean',
'build:transpile',
'test',
['build:lib', 'build:browserify'],
'build:minify',
callback
);
});
gulp.task('sa', ['static-analysis:lint', 'static-analysis:cs']);
gulp.task('ci', function (callback) {
runSequence(
['static-analysis:lint', 'static-analysis:cs'],
'build:clean',
'build:transpile',
'test'
);
});
gulp.task('default', ['build']);

View File

@ -11,24 +11,10 @@ Parse a human readable time string into a time based value.
## Installation ## Installation
### Node
```bash ```bash
npm install --save timestring npm install --save timestring
``` ```
### Browser
```bash
bower install --save timestring
```
Then add a reference to the script in your HTML:
```html
<script src="<path-to-src>/dist/timestring.min.js"></script>
```
## Usage ## Usage
### Overview ### Overview

View File

@ -1,15 +0,0 @@
{
"name": "timestring",
"main": "dist/timestring.js",
"version": "1.1.1",
"description": "Parse a human readable time string into a time based value",
"homepage": "https://github.com/mike182uk/timestring",
"authors": [
"Michael David Barrett <mike182uk@gmail.com>"
],
"license": "MIT",
"ignore": [
"/*",
"!/dist/"
]
}

122
dist/lib/timestring.js vendored

File diff suppressed because one or more lines are too long

126
dist/timestring.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

101
index.js Normal file
View File

@ -0,0 +1,101 @@
module.exports = Timestring;
function Timestring(settings) {
// default settings
var defaults = {
hoursPerDay: 24,
daysPerWeek: 7,
weeksPerMonth: 4,
monthsPerYear: 12,
};
// merge default settings with user settings
settings = settings || {};
this.settings = defaults;
for (var s in settings) { this.settings[s] = settings[s]; }
// time units
this.units = {
s: ['s', 'sec', 'secs', 'second', 'seconds'],
m: ['m', 'min', 'mins', 'minute', 'minutes'],
h: ['h', 'hr', 'hrs', 'hour', 'hours'],
d: ['d', 'day', 'days'],
w: ['w', 'week', 'weeks'],
mth: ['mth', 'mths','month', 'months'],
y: ['y', 'yr', 'yrs', 'year', 'years'],
};
// time unit seconds mappings
this.unitValues = {
s: 1,
m: 60,
h: 3600,
};
// dynamic time unit seconds mappings
// these are dynamic based on the settings
this.unitValues.d = this.settings.hoursPerDay * this.unitValues.h;
this.unitValues.w = this.settings.daysPerWeek * this.unitValues.d;
this.unitValues.mth = this.settings.weeksPerMonth * this.unitValues.w;
this.unitValues.y = this.settings.monthsPerYear * this.unitValues.mth;
}
Timestring.prototype.parse = function(string, returnUnit) {
// reference to this
var that = this;
// get unit key helper
function getUnitKey(unit) {
for (var k in that.units) {
for (var u in that.units[k]) {
if (unit === that.units[k][u]) {
return k;
}
}
}
// throw error if invalid unit was passed
throw new Error('The unit [' + unit + '] is not supported by timestring');
}
// convert a value to a specific unit
function convert(value, unit) {
var baseValue = that.unitValues[getUnitKey(unit)];
return value / baseValue;
}
// get a value in seconds based on a specific unit
function getSeconds(value, unit) {
var baseValue = that.unitValues[getUnitKey(unit)];
return value * baseValue;
}
// seconds counter
var totalSeconds = 0;
// split string into groups and get total seconds for each group
var groups = string
.toLowerCase() // convert words to lower case
.replace(/[^\.\w+-]+/g, '') // remove white space
.match(/[-+]?[0-9]+[a-z]+/g); // match time groups
if (groups !== null) {
for (var i = 0; i < groups.length; i++) {
var g = groups[i];
var value = g.match(/[0-9]+/g)[0];
var unit = g.match(/[a-z]+/g)[0];
totalSeconds += getSeconds(value, unit);
}
}
// return total, convert if needed
return (returnUnit) ? convert(totalSeconds, returnUnit) : totalSeconds;
};
// add convenience method to string prototype
String.prototype.parseTime = function(unit, settings) {
return (new Timestring(settings)).parse(this, unit);
};

View File

@ -8,29 +8,20 @@
"type": "git", "type": "git",
"url": "git://github.com/mike182uk/timestring.git" "url": "git://github.com/mike182uk/timestring.git"
}, },
"main": "dist/lib/timestring.js", "scripts": {
"version": "1.1.1", "sa": "jshint index.js && jscs index.js",
"test": "mocha test.js"
},
"main": "index.js",
"version": "2.0.0",
"devDependencies": { "devDependencies": {
"browserify": "^12.0.1",
"chai": "^3.4.1", "chai": "^3.4.1",
"codeclimate-test-reporter": "^0.1.0", "codeclimate-test-reporter": "^0.1.0",
"coveralls": "^2.11.2", "coveralls": "^2.11.2",
"del": "^2.2.0",
"gulp": "^3.8.11",
"gulp-babel": "^6.1.1",
"gulp-concat": "^2.5.2",
"gulp-jscs": "^3.0.2",
"gulp-jshint": "^2.0.0",
"gulp-load-plugins": "^1.2.0",
"gulp-mocha": "^2.0.1",
"gulp-rename": "^1.2.2",
"gulp-sourcemaps": "^1.5.2",
"gulp-uglify": "^1.2.0",
"istanbul": "^0.4.1", "istanbul": "^0.4.1",
"jshint-stylish": "^2.1.0", "jscs": "^2.8.0",
"jshint": "^2.9.1",
"mocha": "^2.2.4", "mocha": "^2.2.4",
"mocha-lcov-reporter": "1.0.0", "mocha-lcov-reporter": "1.0.0"
"run-sequence": "^1.1.0",
"vinyl-source-stream": "^1.1.0"
} }
} }

View File

@ -1,3 +0,0 @@
String.prototype.parseTime = function( unit, settings ) {
return ( new Timestring( settings ) ).parse( this, unit );
};

View File

@ -1,91 +0,0 @@
export default class Timestring {
constructor( settings = {} ) {
const DEFAULT_SETTINGS = {
hoursPerDay: 24,
daysPerWeek: 7,
weeksPerMonth: 4,
monthsPerYear: 12
};
// merge default settings with user settings
this.settings = DEFAULT_SETTINGS;
for ( let s in settings ) { this.settings[s] = settings[s]; }
// time units
this.units = {
s: [ "s", "sec", "secs", "second", "seconds" ],
m: [ "m", "min", "mins", "minute", "minutes" ],
h: [ "h", "hr", "hrs", "hour", "hours" ],
d: [ "d", "day", "days" ],
w: [ "w", "week", "weeks" ],
mth: [ "mth", "mths", "month", "months" ],
y: [ "y", "yr", "yrs", "year", "years" ]
};
// time unit seconds mappings
this.unitValues = {
s: 1,
m: 60,
h: 3600
};
// dynamic time unit seconds mappings
// these are dynamic based on the settings
this.unitValues.d = this.settings.hoursPerDay * this.unitValues.h;
this.unitValues.w = this.settings.daysPerWeek * this.unitValues.d;
this.unitValues.mth = this.settings.weeksPerMonth * this.unitValues.w;
this.unitValues.y = this.settings.monthsPerYear * this.unitValues.mth;
}
parse( string, returnUnit = "s" ) {
// get unit key helper
let getUnitKey = ( unit ) => {
for ( var k in this.units ) {
for ( var u in this.units[k] ) {
if ( unit === this.units[k][u] ) {
return k;
}
}
}
// throw error if invalid unit was passed
throw new Error( `The unit ${unit} is not supported by timestring` );
};
// convert a value to a specific unit
let convert = ( value, unit ) => {
let baseValue = this.unitValues[getUnitKey( unit )];
return value / baseValue;
};
// get a value in seconds based on a specific unit
let getSeconds = ( value, unit ) => {
let baseValue = this.unitValues[getUnitKey( unit )];
return value * baseValue;
};
// seconds counter
let totalSeconds = 0;
// split string into groups and get total seconds for each group
let groups = string
.toLowerCase() // convert words to lower case
.replace( /[^\.\w+-]+/g, "" ) // remove white space
.match( /[-+]?[0-9]+[a-z]+/g ); // match time groups (digit followed by time unit - i.e 5d 15m = 2 time groups)
if ( groups !== null ) {
for ( let group in groups ) {
let g = groups[group];
let value = g.match( /[0-9]+/g )[0];
let unit = g.match( /[a-z]+/g )[0];
totalSeconds += getSeconds( value, unit );
}
}
return convert( totalSeconds, returnUnit );
}
}

View File

@ -1,7 +1,7 @@
var chai = require('chai'); var chai = require('chai');
var expect = chai.expect; var expect = chai.expect;
var timestring = require('../build/timestring'); var timestring = require('./index');
describe('timestring', function() { describe('timestring', function() {
it('can parse a timestring', function() { it('can parse a timestring', function() {