iso8601-duration
Advanced tools
Comparing version 1.3.0 to 2.0.0-0
153
lib/index.js
@@ -1,10 +0,7 @@ | ||
'use strict'; | ||
Object.defineProperty(exports, "__esModule", { | ||
value: true | ||
}); | ||
"use strict"; | ||
/** | ||
* @description A module for parsing ISO8601 durations | ||
*/ | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.toSeconds = exports.end = exports.parse = exports.pattern = void 0; | ||
/** | ||
@@ -14,89 +11,77 @@ * The pattern used for parsing ISO8601 duration (PnYnMnDTnHnMnS). | ||
*/ | ||
// PnYnMnDTnHnMnS | ||
var numbers = '\\d+(?:[\\.,]\\d+)?'; | ||
var weekPattern = '(' + numbers + 'W)'; | ||
var datePattern = '(' + numbers + 'Y)?(' + numbers + 'M)?(' + numbers + 'D)?'; | ||
var timePattern = 'T(' + numbers + 'H)?(' + numbers + 'M)?(' + numbers + 'S)?'; | ||
var iso8601 = 'P(?:' + weekPattern + '|' + datePattern + '(?:' + timePattern + ')?)'; | ||
var objMap = ['weeks', 'years', 'months', 'days', 'hours', 'minutes', 'seconds']; | ||
var numbers = "\\d+(?:[\\.,]\\d+)?"; | ||
var weekPattern = "(".concat(numbers, "W)"); | ||
var datePattern = "(".concat(numbers, "Y)?(").concat(numbers, "M)?(").concat(numbers, "D)?"); | ||
var timePattern = "T(".concat(numbers, "H)?(").concat(numbers, "M)?(").concat(numbers, "S)?"); | ||
var iso8601 = "P(?:".concat(weekPattern, "|").concat(datePattern, "(?:").concat(timePattern, ")?)"); | ||
var objMap = [ | ||
"weeks", | ||
"years", | ||
"months", | ||
"days", | ||
"hours", | ||
"minutes", | ||
"seconds", | ||
]; | ||
var defaultDuration = Object.freeze({ | ||
years: 0, | ||
months: 0, | ||
weeks: 0, | ||
days: 0, | ||
hours: 0, | ||
minutes: 0, | ||
seconds: 0 | ||
years: 0, | ||
months: 0, | ||
weeks: 0, | ||
days: 0, | ||
hours: 0, | ||
minutes: 0, | ||
seconds: 0, | ||
}); | ||
/** | ||
* The ISO8601 regex for matching / testing durations | ||
*/ | ||
var pattern = exports.pattern = new RegExp(iso8601); | ||
/** Parse PnYnMnDTnHnMnS format to object | ||
* @param {string} durationString - PnYnMnDTnHnMnS formatted string | ||
* @return {Object} - With a property for each part of the pattern | ||
*/ | ||
var parse = exports.parse = function parse(durationString) { | ||
// Slice away first entry in match-array | ||
return durationString.match(pattern).slice(1).reduce(function (prev, next, idx) { | ||
prev[objMap[idx]] = parseFloat(next) || 0; | ||
return prev; | ||
}, {}); | ||
exports.pattern = new RegExp(iso8601); | ||
/** Parse PnYnMnDTnHnMnS format to object */ | ||
var parse = function (durationString) { | ||
// Slice away first entry in match-array | ||
return durationString | ||
.match(exports.pattern) | ||
.slice(1) | ||
.reduce(function (prev, next, idx) { | ||
prev[objMap[idx]] = parseFloat(next) || 0; | ||
return prev; | ||
}, {}); | ||
}; | ||
/** | ||
* Convert ISO8601 duration object to an end Date. | ||
* | ||
* @param {Object} duration - The duration object | ||
* @param {Date} startDate - The starting Date for calculating the duration | ||
* @return {Date} - The resulting end Date | ||
*/ | ||
var end = exports.end = function end(duration, startDate) { | ||
duration = Object.assign({}, defaultDuration, duration); | ||
// Create two equal timestamps, add duration to 'then' and return time difference | ||
var timestamp = startDate ? startDate.getTime() : Date.now(); | ||
var then = new Date(timestamp); | ||
then.setFullYear(then.getFullYear() + duration.years); | ||
then.setMonth(then.getMonth() + duration.months); | ||
then.setDate(then.getDate() + duration.days); | ||
then.setHours(then.getHours() + duration.hours); | ||
then.setMinutes(then.getMinutes() + duration.minutes); | ||
// Then.setSeconds(then.getSeconds() + duration.seconds); | ||
then.setMilliseconds(then.getMilliseconds() + duration.seconds * 1000); | ||
// Special case weeks | ||
then.setDate(then.getDate() + duration.weeks * 7); | ||
return then; | ||
exports.parse = parse; | ||
/** Convert ISO8601 duration object to an end Date. */ | ||
var end = function (durationInput, startDate) { | ||
if (startDate === void 0) { startDate = new Date(); } | ||
var duration = Object.assign({}, defaultDuration, durationInput); | ||
// Create two equal timestamps, add duration to 'then' and return time difference | ||
var timestamp = startDate.getTime(); | ||
var then = new Date(timestamp); | ||
then.setFullYear(then.getFullYear() + duration.years); | ||
then.setMonth(then.getMonth() + duration.months); | ||
then.setDate(then.getDate() + duration.days); | ||
then.setHours(then.getHours() + duration.hours); | ||
then.setMinutes(then.getMinutes() + duration.minutes); | ||
// Then.setSeconds(then.getSeconds() + duration.seconds); | ||
then.setMilliseconds(then.getMilliseconds() + duration.seconds * 1000); | ||
// Special case weeks | ||
then.setDate(then.getDate() + duration.weeks * 7); | ||
return then; | ||
}; | ||
/** | ||
* Convert ISO8601 duration object to seconds | ||
* | ||
* @param {Object} duration - The duration object | ||
* @param {Date} startDate - The starting point for calculating the duration | ||
* @return {Number} | ||
*/ | ||
var toSeconds = exports.toSeconds = function toSeconds(duration, startDate) { | ||
duration = Object.assign({}, defaultDuration, duration); | ||
var timestamp = startDate ? startDate.getTime() : Date.now(); | ||
var now = new Date(timestamp); | ||
var then = end(duration, now); | ||
var seconds = (then.getTime() - now.getTime()) / 1000; | ||
return seconds; | ||
exports.end = end; | ||
/** Convert ISO8601 duration object to seconds */ | ||
var toSeconds = function (durationInput, startDate) { | ||
if (startDate === void 0) { startDate = new Date(); } | ||
var duration = Object.assign({}, defaultDuration, durationInput); | ||
var timestamp = startDate.getTime(); | ||
var now = new Date(timestamp); | ||
var then = (0, exports.end)(duration, now); | ||
var seconds = (then.getTime() - now.getTime()) / 1000; | ||
return seconds; | ||
}; | ||
exports.toSeconds = toSeconds; | ||
exports.default = { | ||
end: end, | ||
toSeconds: toSeconds, | ||
pattern: pattern, | ||
parse: parse | ||
}; | ||
end: exports.end, | ||
toSeconds: exports.toSeconds, | ||
pattern: exports.pattern, | ||
parse: exports.parse, | ||
}; |
{ | ||
"name": "iso8601-duration", | ||
"version": "1.3.0", | ||
"version": "2.0.0-0", | ||
"description": "Node/Js-module for parsing and making sense of ISO8601-durations", | ||
"main": "lib/index.js", | ||
"types": "index.d.ts", | ||
"jsnext:main": "src/index.js", | ||
"types": "lib/index.d.ts", | ||
"scripts": { | ||
"lint": "standard | snazzy", | ||
"test": "npm run lint && ava && tsc", | ||
"lint": "prettier --write .", | ||
"test": "npm run lint && npm run unittests", | ||
"unittests": "uvu -r ts-node/register test", | ||
"watch": "onchange '**/*.js' -- npm run test", | ||
"compile": "babel -d lib/ src/", | ||
"compile": "tsc", | ||
"prepublishOnly": "npm run compile", | ||
"patch-release": "npm test && npm version patch && git push --follow-tags" | ||
"release-patch": "npx np patch", | ||
"release-beta": "npx np --tag=beta" | ||
}, | ||
"files": [ | ||
"src/index.js", | ||
"lib/index.js", | ||
"index.d.ts" | ||
"lib/index.d.ts" | ||
], | ||
@@ -37,25 +37,8 @@ "repository": { | ||
"devDependencies": { | ||
"ava": "^0.22.0", | ||
"babel-cli": "^6.4.0", | ||
"babel-preset-es2015": "^6.3.13", | ||
"onchange": "^3.2.1", | ||
"snazzy": "^7.0.0", | ||
"standard": "^10.0.3", | ||
"typescript": "^3.0.3" | ||
}, | ||
"standard": { | ||
"ignore": [ | ||
"lib/*.js" | ||
] | ||
}, | ||
"ava": { | ||
"files": [ | ||
"test/*.js" | ||
], | ||
"failFast": true, | ||
"verbose": true, | ||
"require": [ | ||
"babel-core/register" | ||
] | ||
"onchange": "^3.3.0", | ||
"prettier": "^2.6.2", | ||
"ts-node": "^10.7.0", | ||
"typescript": "4.6.3", | ||
"uvu": "^0.5.3" | ||
} | ||
} |
# ISO8601-duration | ||
Node/Js-module for parsing and making sense of ISO8601-durations | ||
[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)][1] | ||
[![Build Status: Travis](https://img.shields.io/travis/tolu/ISO8601-duration/master.svg)][2] | ||
[![npm version](https://img.shields.io/npm/v/iso8601-duration.svg)][3] | ||
[![Build Status: Travis](https://img.shields.io/travis/tolu/ISO8601-duration/master.svg)][travis] | ||
[![npm version](https://img.shields.io/npm/v/iso8601-duration.svg)][npm] | ||
![npm bundle size][bundlephobia] | ||
> A new standard is on it's way, see [Temporal.Duration](https://tc39.es/proposal-temporal/docs/duration.html) | ||
## The ISO8601 duration format | ||
Durations in ISO8601 comes in two formats: | ||
* **`PnYnMnDTnHnMnS`** - `P<date>T<time>` | ||
- **`PnYnMnDTnHnMnS`** - `P<date>T<time>` | ||
The `n` is replaced by the value for each of the date and time elements that follow the `n`. | ||
Leading zeros are not required | ||
* **`PnW`** - the week format | ||
- **`PnW`** - the week format | ||
Check out the details on [Wikipedia](https://en.wikipedia.org/wiki/ISO_8601#Durations) | ||
Check out the details on [Wikipedia](https://en.wikipedia.org/wiki/ISO_8601#Durations) | ||
## Install | ||
```sh | ||
npm install iso8601-duration | ||
``` | ||
$ npm install iso8601-duration | ||
``` | ||
## Usage | ||
Most noteworthy of the interface is the ability to provide a `date` for `toSeconds`-calculations. | ||
Why becomes evident when working with durations that span dates as all months are not equally long. | ||
E.g January of 2016 is **744 hours** compared to the **696 hours** of February 2016. | ||
E.g January of 2016 is **744 hours** compared to the **696 hours** of February 2016. | ||
If a date is not provided for `toSeconds` the timestamp `Date.now()` is used as baseline. | ||
If a date is not provided for `toSeconds` the timestamp `Date.now()` is used as baseline. | ||
@@ -46,7 +50,9 @@ ### Interface | ||
### Example | ||
Simple usage | ||
```js | ||
import {parse, end, toSeconds, pattern} from 'iso8601-duration'; | ||
import { parse, end, toSeconds, pattern } from "iso8601-duration"; | ||
console.log(parse('P1Y2M4DT20H44M12.67S')); | ||
console.log(parse("P1Y2M4DT20H44M12.67S")); | ||
/* outputs => | ||
@@ -63,38 +69,35 @@ { | ||
console.log( toSeconds( parse('PT1H30M10.5S') ) ); | ||
console.log(toSeconds(parse("PT1H30M10.5S"))); | ||
// outputs => 5410.5 | ||
console.log ( end( parse('P1D') ) ); | ||
console.log(end(parse("P1D"))); | ||
// outputs => DateObj 2017-10-04T10:14:50.190Z | ||
``` | ||
A more complete usecase / example | ||
```js | ||
import {parse, toSeconds, pattern} from 'iso8601-duration'; | ||
import { parse, toSeconds, pattern } from "iso8601-duration"; | ||
// convert iso8601 duration-strings to total seconds from some api | ||
const getWithSensibleDurations = someApiEndpoint => { | ||
// return promise, like fetch does | ||
return new Promise(resolve => { | ||
// fetch text | ||
fetch(someApiEndpoint) | ||
.then(res => res.text()) | ||
.then(jsonString => { | ||
// create new pattern that matches on surrounding double-quotes | ||
// so we can replace the string with an actual number | ||
const replacePattern = new RegExp(`\\"${pattern.source}\\"`, 'g'); | ||
jsonString = jsonString.replace(replacePattern, m => { | ||
return toSeconds(parse(m)); | ||
}); | ||
// resolve original request with sensible durations in object | ||
resolve( JSON.parse(jsonString) ); | ||
}); | ||
}); | ||
} | ||
const getWithSensibleDurations = (someApiEndpoint) => { | ||
// return promise, like fetch does | ||
return new Promise((resolve) => { | ||
// fetch text | ||
fetch(someApiEndpoint) | ||
.then((res) => res.text()) | ||
.then((jsonString) => { | ||
// create new pattern that matches on surrounding double-quotes | ||
// so we can replace the string with an actual number | ||
const replacePattern = new RegExp(`\\"${pattern.source}\\"`, "g"); | ||
jsonString = jsonString.replace(replacePattern, (m) => { | ||
return toSeconds(parse(m)); | ||
}); | ||
// resolve original request with sensible durations in object | ||
resolve(JSON.parse(jsonString)); | ||
}); | ||
}); | ||
}; | ||
``` | ||
## License | ||
@@ -104,4 +107,4 @@ | ||
[1]: https://github.com/sindresorhus/xo "xo on github" | ||
[2]: https://travis-ci.org/tolu/ISO8601-duration "travis build status" | ||
[3]: https://www.npmjs.com/package/iso8601-duration "npm package" | ||
[travis]: https://travis-ci.org/tolu/ISO8601-duration "travis build status" | ||
[npm]: https://www.npmjs.com/package/iso8601-duration "npm package" | ||
[bundlephobia]: https://img.shields.io/bundlephobia/minzip/iso8601-duration |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
5
108
8015
4
115
1
1