Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

moment-duration-format

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

moment-duration-format - npm Package Compare versions

Comparing version 1.2.2 to 1.3.0

2

bower.json
{
"name": "moment-duration-format",
"version": "1.2.2",
"version": "1.3.0",
"description": "A moment.js plugin for formatting durations.",

@@ -5,0 +5,0 @@ "main": "lib/moment-duration-format.js",

@@ -1,4 +0,4 @@

/*! Moment Duration Format v1.2.2
/*! Moment Duration Format v1.3.0
* https://github.com/jsmreese/moment-duration-format
* Date: 2014-07-10
* Date: 2014-07-15
*

@@ -17,3 +17,3 @@ * Duration format plugin function for the Moment.js library

function repeatZero(qty) {
var result;
var result = "";

@@ -24,6 +24,4 @@ // exit early

qty = parseInt(qty, 10);
if (!qty || qty < 1) { return ""; }
if (!qty || qty < 1) { return result; }
result = "";
while (qty) {

@@ -49,42 +47,155 @@ result += "0";

}
// findLast roughly lifted from Lo-Dash
// used if _.findLast does not exist
function findLast (array, callback) {
var index = array.length,
last;
// isArray
function isArray(array) {
return Object.prototype.toString.call(array) === "[object Array]";
}
// isObject
function isObject(obj) {
return Object.prototype.toString.call(obj) === "[object Object]";
}
// findLast
function findLast(array, callback) {
var index = array.length;
while (index--) {
if (callback(array[index]) > 0) {
last = array[index];
break;
}
while (index -= 1) {
if (callback(array[index])) { return array[index]; }
}
}
return last;
// find
function find(array, callback) {
var index = 0,
max = array.length,
match;
if (typeof callback !== "function") {
match = callback;
callback = function (item) {
return item === match;
};
}
while (index < max) {
if (callback(array[index])) { return array[index]; }
index += 1;
}
}
// each
function each(array, callback) {
var index = 0,
max = array.length;
// define internal moment and _ references
var moment, _,
hasRequire = (typeof require === "function");
if (!array || !max) { return; }
if (hasRequire) {
// require lodash or underscore
try {
_ = require('lodash');
} catch (e) {
_ = require('underscore');
while (index < max) {
if (callback(array[index], index) === false) { return; }
index += 1;
}
} else if (root._) {
_ = root._;
} else {
throw "Moment Duration Format cannot find Lo-Dash or Underscore";
}
if (hasRequire) {
// require moment
moment = require('moment');
} else if (root.moment) {
// map
function map(array, callback) {
var index = 0,
max = array.length,
ret = [];
if (!array || !max) { return ret; }
while (index < max) {
ret[index] = callback(array[index], index);
index += 1;
}
return ret;
}
// pluck
function pluck(array, prop) {
return map(array, function (item) {
return item[prop];
});
}
// compact
function compact(array) {
var ret = [];
each(array, function (item) {
if (item) { ret.push(item); }
});
return ret;
}
// unique
function unique(array) {
var ret = [];
each(array, function (_a) {
if (!find(ret, _a)) { ret.push(_a); }
});
return ret;
}
// intersection
function intersection(a, b) {
var ret = [];
each(a, function (_a) {
each(b, function (_b) {
if (_a === _b) { ret.push(_a); }
});
});
return unique(ret);
}
// rest
function rest(array, callback) {
var ret = [];
each(array, function (item, index) {
if (!callback(item)) {
ret = array.slice(index);
return false;
}
});
return ret;
}
// initial
function initial(array, callback) {
var reversed = array.slice().reverse();
return rest(reversed, callback).reverse();
}
// extend
function extend(a, b) {
for (var key in b) {
if (b.hasOwnProperty(key)) { a[key] = b[key]; }
}
return a;
}
// define internal moment reference
var moment;
if (typeof require === "function") {
try { moment = require('moment'); }
catch (e) {}
}
if (!moment && root.moment) {
moment = root.moment;
} else {
}
if (!moment) {
throw "Moment Duration Format cannot find Moment.js";

@@ -98,3 +209,3 @@ }

args = [].slice.call(arguments),
settings = _.extend({}, this.format.defaults),
settings = extend({}, this.format.defaults),
// keep a shadow copy of this moment for calculating remainders

@@ -108,3 +219,3 @@ remainder = moment.duration(this);

// parse arguments
_.each(args, function (arg) {
each(args, function (arg) {
if (typeof arg === "string" || typeof arg === "function") {

@@ -120,4 +231,4 @@ settings.template = arg;

if (_.isObject(arg)) {
_.extend(settings, arg);
if (isObject(arg)) {
extend(settings, arg);
}

@@ -127,3 +238,3 @@ });

// types
types = settings.types = (_.isArray(settings.types) ? settings.types : settings.types.split(" "));
types = settings.types = (isArray(settings.types) ? settings.types : settings.types.split(" "));

@@ -136,3 +247,3 @@ // template

// tokenizer regexp
tokenizer = new RegExp(_.map(types, function (type) {
tokenizer = new RegExp(map(types, function (type) {
return settings[type].source;

@@ -143,3 +254,3 @@ }).join("|"), "g");

typeMap = function (token) {
return _.find(types, function (type) {
return find(types, function (type) {
return settings[type].test(token);

@@ -150,3 +261,3 @@ });

// tokens array
tokens = _.map(settings.template.match(tokenizer), function (token, index) {
tokens = map(settings.template.match(tokenizer), function (token, index) {
var type = typeMap(token),

@@ -171,11 +282,11 @@ length = token.length;

// unique moment token types in the template (in order of descending magnitude)
momentTypes = _.intersection(types, _.unique(_.compact(_.pluck(tokens, "type"))));
momentTypes = intersection(types, unique(compact(pluck(tokens, "type"))));
// exit early if there are no momentTypes
if (!momentTypes.length) {
return _.pluck(tokens, "token").join("");
return pluck(tokens, "token").join("");
}
// calculate values for each token type in the template
_.each(momentTypes, function (momentType, index) {
each(momentTypes, function (momentType, index) {
var value, wholeValue, decimalValue, isLeast, isMost;

@@ -197,5 +308,5 @@

// the order or frequency of any tokens
_.each(tokens, function (token) {
each(tokens, function (token) {
if (token.type === momentType) {
_.extend(token, {
extend(token, {
value: value,

@@ -227,29 +338,6 @@ wholeValue: wholeValue,

});
// trim tokens array
if (settings.trim) {
// manually identifying trim index because undescore does not support callback functions on rest/initial or indexOf/lastIndexOf
foundFirst = false;
trimIndex = _[settings.trim === "left" ? "reduce" : "reduceRight"](tokens, function (trimIndex, token, tokenIndex) {
// return tokenIndex if:
// the token is not the least moment token (don't trim the least moment token)
// the token is a moment token that does not have a value (don't trim moment tokens that have a whole value)
if (!(foundFirst || (token.isLeast || (token.type != null && token.wholeValue)))) {
return tokenIndex;
}
foundFirst = true;
return trimIndex;
}, -1);
if (trimIndex !== -1) {
tokens = _[settings.trim === "left" ? "rest" : "first"](tokens, settings.trim === "left" ? trimIndex + 1 : trimIndex);
}
}
/*
// trim tokens array: simpler version that used Lo-Dash callback functions on rest/initial
if (settings.trim) {
tokens = _[settings.trim === "left" ? "rest" : "initial"](tokens, function (token) {
tokens = (settings.trim === "left" ? rest : initial)(tokens, function (token) {
// return `true` if:

@@ -261,4 +349,4 @@ // the token is not the least moment token (don't trim the least moment token)

}
*/
// build output

@@ -274,3 +362,3 @@

tokens = _.map(tokens, function (token) {
tokens = map(tokens, function (token) {
var val,

@@ -383,13 +471,5 @@ decVal;

dur = this.duration,
lastType;
if (typeof _.findLast === "function") {
lastType = _.findLast(types, function (type) {
return dur._data[type];
});
} else {
lastType = findLast(types, function (type) {
return dur._data[type];
});
}

@@ -396,0 +476,0 @@ // default template strings for each duration dimension type

{
"name": "moment-duration-format",
"version": "1.2.2",
"version": "1.3.0",
"description": "A moment.js plugin for formatting durations.",

@@ -5,0 +5,0 @@ "main": "lib/moment-duration-format.js",

@@ -1,4 +0,4 @@

#Moment Duration Format
# Moment Duration Format
###Format plugin for the Moment Duration object.
**Format plugin for the Moment Duration object.**

@@ -9,24 +9,27 @@ This is a plugin to the Moment.js JavaScript date library to add comprehensive formatting to Moment Durations.

This plugin depends on <a href="http://lodash.com/">Lo-Dash</a> or <a href="http://http://underscorejs.org//">Underscore</a>, and is tested with both libraries.
This plugin does not have any dependencies beyond Moment.js itself, and may be used in the browser and in Node.js.
---
### Installation
## Installation
##### Node.js
**Node.js**
`npm install moment-duration-format`
##### Bower
**Bower**
`bower install moment-duration-format`
##### Browser
**Browser**
`<script src="path/to/moment-duration-format.js"></script>`
Be sure to include moment.js and lodash.js or underscore.js on your page before loading this plugin.
When using this plugin in the browser, be sure to include moment.js on your page first.
---
### Usage
## Usage
##### Module
### Module

@@ -40,6 +43,16 @@ To use this plugin as a module, use the `require` function:

The plugin depends on moment.js and lodash.js or underscore.js. These are not specified as package dependencies in the currently published plugin version.
The plugin depends on moment.js, which is not specified as a package dependency in the currently published version.
##### Arguments
### Basics
The duration format method can format any moment duration. If no template or other arguments are provided, the default template function will generate a template string based on the duration's value.
```
moment.duration(123, "minutes").format();
// "2:03:00"
moment.duration(123, "months").format();
// "10y 3m"
```
The duration format method may be called with three optional arguments:

@@ -50,5 +63,13 @@ ```

`template` is a string. It is parsed for moment-token characters, which are replaced with the duration value for that type.
Moment-tokens may be be customized (see test cases for examples), but the default token map is:
### Template
`template` (string|function) is the string used to create the formatted output, or a function that returns the string to be used as the format template.
```
moment.duration(123, "minutes").format("h:mm");
// "2:03"
```
The template string is parsed for moment-token characters, which are replaced with the duration's value for each unit type. The default tokens are:
```
years: Y or y

@@ -64,41 +85,192 @@ months: M

`precision` is an integer. Positive precision defines the number of decimal digits to display. Negative precision will truncate the value to the left of the decimal point.
Token characters may be customized ([see below for an example](\#tokens)).
Both the `template` and `precision` arguments may be specified as properties of a single `settings` object argument if desired, or they may be passed separately along with an optional settings object.
Escape token characters within the template string using square brackets.
```
moment.duration(123, "minutes").format("h [hrs], m [min]");
// "2 hrs, 3 min"
```
Escape characters may also be customized ([see below for an example](\#escape)).
##### Basics
```
moment.duration(123, "minutes").format();
// "2:03:00"
moment.duration(123, "minutes").format("h:mm");
// "2:03"
moment.duration(123, "minutes").format("h [hrs], m [min]");
// "2 hrs, 3 min"
// escape moment-tokens using square brackets
// this can be customized using `settings.escape`
### Precision
`precision` (number) defines the number of digits to display for the final value.
The default precison value is `0`.
```
moment.duration(123, "minutes").format("h [hrs]");
// "2 hrs"
```
Positive precision defines the number of digits to display to the right of the decimal point.
```
moment.duration(123, "minutes").format("h [hrs]", 2);
// "2.04 hrs"
// show arbitrary decimal precision with positive precision
```
Negative precision will truncate the value to the left of the decimal point.
```
moment.duration(123, "minutes").format("m [min]", -1);
// "120 min"
// truncate the final value with negative precision
```
### Settings
`settings` is an object that can override any of the default moment duration format options.
Both the `template` and `precision` arguments may be specified as properties of a single `settings` object argument, or they may be passed separately along with an optional settings object.
```
moment.duration(123, "minutes").format({ template: "h [hrs]", precision: 2 });
// "2.04 hrs"
```
#### Trim
Leading tokens are automatically trimmed when they have no value.
```
moment.duration(123, "minutes").format("d[d] h:mm:ss");
// "2:03:00"
// automatically trim leading tokens that have no value
```
To stop that behavior, set `{ trim: false }`.
```
moment.duration(123, "minutes").format("d[d] h:mm:ss", { trim: false });
// "0d 2:03:00"
```
Use `{ trim: "right" }` to trim from the right.
```
moment.duration(123, "minutes").format("[seconds:] s -- [minutes:] m -- [hours:] h -- [days:] d", { trim: "right" });
// "seconds: 0 -- minutes: 3 -- hours: 2"
// or trim from the right
```
moment.duration(123, "minutes").format("d[d] h:mm:ss", { trim: false });
// "0d 2:03:00"
// or don't trim at all
#### Force Length
Force the first moment token with a value to render at full length, even when the template is trimmed and the first moment token has a length of 1. Sounds more complicated than it is.
```
moment.duration(123, "seconds").format("h:mm:ss");
// "2:03"
```
See the test cases and the default settings for more thorough option descriptions.
If you want minutes to always be rendered with two digits, you can set the first token to a length greater than 1 (this stops the automatic length trimming for the first token that has a value).
```
moment.duration(123, "seconds").format("hh:mm:ss");
// "02:03"
```
Or you can use `{ forceLength: true }`.
```
moment.duration(123, "seconds").format("h:mm:ss", { forceLength: true });
// "02:03"
```
### Tokens
Moment tokens are defined as regular expressions, and may be customized. Token definitions may be passed in the settings object, but are more likely set on the defaults object.
#### Escape
Default escape token regexp: `/\[(.+?)\]/`
Define something other than square brackets as escape characters.
```
moment.duration.fn.format.defaults.escape = /\((.+?)\)/;
moment.duration(123, "seconds").format("m (minutes)", 2);
// "2.04 minutes"
```
#### Years
Default years token regexp: `/[Yy]+/`
Define years token for spanish language formatting.
```
moment.duration.fn.format.defaults.years = /[Aa]+/;
moment.duration(123, "weeks").format("a [años]", 2);
// "2.35 años"
```
#### Months
Default months token regexp: `/M+/`
Define months token to use only lower-case `m`.
```
moment.duration.fn.format.defaults.months = /m+/;
moment.duration(123, "weeks").format("m M", 2);
// "28.36 M"
```
#### Weeks
Default weeks token regexp: `/[Ww]+/`
Define weeks token to use only lower-case `w`.
```
moment.duration.fn.format.defaults.weeks = /w+/;
moment.duration(123, "days").format("w W", 2);
// "17.57 W"
```
#### Days
Default days token regexp: `/[Dd]+/`
Define days token to use only lower-case `d`.
```
moment.duration.fn.format.defaults.days = /d+/;
moment.duration(123, "hours").format("d D", 2);
// "5.12 D"
```
#### Hours
Default hours token regexp: `/[Hh]+/`
Define hours token to use only lower-case `h`.
```
moment.duration.fn.format.defaults.hours = /h+/;
moment.duration(123, "minutes").format("h H", 2);
// "2.04 H"
```
#### Minutes
Default minutes token regexp: `/m+/`
Define minutes token to use only lower-case `n`.
```
moment.duration.fn.format.defaults.minutes = /n+/;
moment.duration(123, "seconds").format("n:ss");
// "2:03"
```
#### Seconds
Default seconds token regexp: `/s+/`
#### Milliseconds
Default milliseconds token regexp: `/S+/`
#### General
Default general token regexp: `/.+?/`
Not sure why you'd want to redefine the general token regexp, but you can. Just make sure it's lazy so the other token expressions can do their jobs.

@@ -152,6 +152,22 @@ $(document).ready(function() {

equal(moment.duration(100, "days").format(function () {
// map
function map(array, callback) {
var index = 0,
max = array.length,
ret = [];
if (!array || !max) { return ret; }
while (index < max) {
ret[index] = callback(array[index], index);
index += 1;
}
return ret;
}
var types = this.types,
dur = this.duration;
return _.map(types.slice(1, -2), function (type) {
return map(types.slice(1, -2), function (type) {
return ((type === "months" || type === "milliseconds") ? type[0].toUpperCase() : type[0]) + " [" + type + "]";

@@ -158,0 +174,0 @@ }).join(", ");

@@ -0,0 +0,0 @@ /**

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc