Skip to content

Commit

Permalink
prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
tolu committed Apr 12, 2022
1 parent b39ac80 commit 52cef12
Show file tree
Hide file tree
Showing 5 changed files with 134 additions and 110 deletions.
30 changes: 15 additions & 15 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
language: node_js
node_js:
- '14'
- '6'
- "16"
- "6"
before_install:
- npm i -g npm@latest
- npm i -g npm@latest
jobs:
include:
- stage: npm release
node_js: '12'
deploy:
provider: npm
email: tobias.lundin@gmail.com
api_key:
secure: Ws23UHDCaIU7NiadyaS4tQJk1qjJe6SQaSCYXkFYH+kRZBh+k3OLfYBNBdYNcdgyNembB1JiGQzE5bE/eVVz+c8B4tX0fWDb69jc9suRfd84BnnwJbRuvXMOz9Ftl80C28b1SuGaKccPCeMP2iENLkAIi7I0LwVlgy6gUoVohmFq3V7YhWe7VLkpoUu8PA/TZqZv7E9GIaEH0vOXJLtEEeCNbnbzRdhU4ovCSbj9PxPESwktqU0dQVwBu4AUR6hmYAOkE8M0fcXYqGv2IpcuWplkr7PBbRCH22THoaxNO9ZdEFDXstTL9NIa8fYNFAf5sTKEvWo5fYuYDHITu4ckdj8/PG1l5lB2TrkREbKCOSDiK4BtZiE4vlFVBEXmLD8MV3oqDy5aQWpiUDJgiJfiGMawjIM3jJ1SaJc7PVIrO8M4CptQTR8oYwOyhIHQTOS34+H4WsOzXaaAJVu6bLBQWigfDYoL7w4NRRsY7ZrkEvvgs3nfWja740NA0CIXid9Cd9fzDA7ju8RRHADjYIUIrdNIBL2ZU00AaoHFeCxMrZvdpCt/OG6bh2UAR8qR+94Ri4IgaHIkC8xNLNeFXycAmcScXD6UXMQbSfL8hjBJIgA1ztyE2XD50qwn65eaJ1r14st4HMgi5QVPc25VSuBDaOFHG84TY0tKfvhRKLFjoh0=
skip_cleanup: true
on:
tags: true
repo: tolu/ISO8601-duration
branch: master
- stage: npm release
node_js: "16"
deploy:
provider: npm
email: tobias.lundin@gmail.com
api_key:
secure: Ws23UHDCaIU7NiadyaS4tQJk1qjJe6SQaSCYXkFYH+kRZBh+k3OLfYBNBdYNcdgyNembB1JiGQzE5bE/eVVz+c8B4tX0fWDb69jc9suRfd84BnnwJbRuvXMOz9Ftl80C28b1SuGaKccPCeMP2iENLkAIi7I0LwVlgy6gUoVohmFq3V7YhWe7VLkpoUu8PA/TZqZv7E9GIaEH0vOXJLtEEeCNbnbzRdhU4ovCSbj9PxPESwktqU0dQVwBu4AUR6hmYAOkE8M0fcXYqGv2IpcuWplkr7PBbRCH22THoaxNO9ZdEFDXstTL9NIa8fYNFAf5sTKEvWo5fYuYDHITu4ckdj8/PG1l5lB2TrkREbKCOSDiK4BtZiE4vlFVBEXmLD8MV3oqDy5aQWpiUDJgiJfiGMawjIM3jJ1SaJc7PVIrO8M4CptQTR8oYwOyhIHQTOS34+H4WsOzXaaAJVu6bLBQWigfDYoL7w4NRRsY7ZrkEvvgs3nfWja740NA0CIXid9Cd9fzDA7ju8RRHADjYIUIrdNIBL2ZU00AaoHFeCxMrZvdpCt/OG6bh2UAR8qR+94Ri4IgaHIkC8xNLNeFXycAmcScXD6UXMQbSfL8hjBJIgA1ztyE2XD50qwn65eaJ1r14st4HMgi5QVPc25VSuBDaOFHG84TY0tKfvhRKLFjoh0=
skip_cleanup: true
on:
tags: true
repo: tolu/ISO8601-duration
branch: master
69 changes: 35 additions & 34 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# ISO8601-duration

Node/Js-module for parsing and making sense of ISO8601-durations

[![Build Status: Travis](https://img.shields.io/travis/tolu/ISO8601-duration/master.svg)][travis]
Expand All @@ -8,13 +9,13 @@ Node/Js-module for parsing and making sense of ISO8601-durations
## 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

Expand All @@ -23,11 +24,12 @@ $ 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.

### Interface

Expand All @@ -43,11 +45,13 @@ export default {
```

### 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 =>
{
years: 1,
Expand All @@ -59,46 +63,43 @@ console.log(parse('P1Y2M4DT20H44M12.67S'));
}
*/

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

MIT @ https://tolu.mit-license.org/

[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
[bundlephobia]: https://img.shields.io/bundlephobia/minzip/iso8601-duration
56 changes: 34 additions & 22 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';
"use strict";

Object.defineProperty(exports, "__esModule", {
value: true
value: true,
});
/**
* @description A module for parsing ISO8601 durations
Expand All @@ -13,13 +13,22 @@ Object.defineProperty(exports, "__esModule", {
*/

// 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 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 iso8601 =
"P(?:" + weekPattern + "|" + datePattern + "(?:" + timePattern + ")?)";
var objMap = [
"weeks",
"years",
"months",
"days",
"hours",
"minutes",
"seconds",
];

var defaultDuration = Object.freeze({
years: 0,
Expand All @@ -28,25 +37,28 @@ var defaultDuration = Object.freeze({
days: 0,
hours: 0,
minutes: 0,
seconds: 0
seconds: 0,
});

/**
* The ISO8601 regex for matching / testing durations
*/
var pattern = exports.pattern = new RegExp(iso8601);
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) {
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;
}, {});
};
return durationString
.match(pattern)
.slice(1)
.reduce(function (prev, next, idx) {
prev[objMap[idx]] = parseFloat(next) || 0;
return prev;
}, {});
});

/**
* Convert ISO8601 duration object to an end Date.
Expand All @@ -55,7 +67,7 @@ var parse = exports.parse = function parse(durationString) {
* @param {Date} startDate - The starting Date for calculating the duration
* @return {Date} - The resulting end Date
*/
var end = exports.end = function end(duration, startDate) {
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
Expand All @@ -73,7 +85,7 @@ var end = exports.end = function end(duration, startDate) {
then.setDate(then.getDate() + duration.weeks * 7);

return then;
};
});

/**
* Convert ISO8601 duration object to seconds
Expand All @@ -82,7 +94,7 @@ var end = exports.end = function end(duration, startDate) {
* @param {Date} startDate - The starting point for calculating the duration
* @return {Number}
*/
var toSeconds = exports.toSeconds = function toSeconds(duration, startDate) {
var toSeconds = (exports.toSeconds = function toSeconds(duration, startDate) {
duration = Object.assign({}, defaultDuration, duration);

var timestamp = startDate ? startDate.getTime() : Date.now();
Expand All @@ -91,11 +103,11 @@ var toSeconds = exports.toSeconds = function toSeconds(duration, startDate) {

var seconds = (then.getTime() - now.getTime()) / 1000;
return seconds;
};
});

exports.default = {
end: end,
toSeconds: toSeconds,
pattern: pattern,
parse: parse
};
parse: parse,
};
Loading

0 comments on commit 52cef12

Please sign in to comment.