chore(6.0): remove rollup package
diff --git a/.bazelrc b/.bazelrc index d6fd2b1..e009717 100644 --- a/.bazelrc +++ b/.bazelrc
@@ -5,8 +5,8 @@ # This lets us glob() up all the files inside the examples to make them inputs to tests # To update these lines, just run `yarn bazel:update-deleted-packages` # (Note, we cannot use common --deleted_packages because the bazel version command doesn't support it) -build --deleted_packages=e2e/bazel_run_chdir,e2e/bazel_run_chdir/subfolder,e2e/fine_grained_symlinks,e2e/linker_disabled_regression,e2e/linker_disabled_regression/subdir,e2e/node_loader_preserve_symlinks,e2e/nodejs_host,e2e/nodejs_image,e2e/nodejs_image/foolib,e2e/packages,e2e/symlinked_node_modules_npm,e2e/symlinked_node_modules_yarn,e2e/webapp,examples/angular,examples/angular/src,examples/angular/src/app,examples/angular/src/app/hello-world,examples/angular/src/app/home,examples/angular/src/app/todos,examples/angular/src/app/todos/reducers,examples/angular/src/assets,examples/angular/src/lib/shorten,examples/angular/src/shared/material,examples/angular/tools,examples/angular_bazel_architect,examples/angular_bazel_architect/projects/frontend-lib,examples/app,examples/app/styles,examples/app/test,examples/closure,examples/create-react-app,examples/from_source,examples/jest,examples/jest/ts,examples/jest/ts/src,examples/jest/ts/test,examples/kotlin,examples/nestjs,examples/nestjs/src,examples/parcel,examples/protobufjs,examples/react_webpack,examples/toolchain,examples/vue,examples/vue/src,examples/vue/src/components/HelloWorld,examples/web_testing,examples/webapp,examples/worker -query --deleted_packages=e2e/bazel_run_chdir,e2e/bazel_run_chdir/subfolder,e2e/fine_grained_symlinks,e2e/linker_disabled_regression,e2e/linker_disabled_regression/subdir,e2e/node_loader_preserve_symlinks,e2e/nodejs_host,e2e/nodejs_image,e2e/nodejs_image/foolib,e2e/packages,e2e/symlinked_node_modules_npm,e2e/symlinked_node_modules_yarn,e2e/webapp,examples/angular,examples/angular/src,examples/angular/src/app,examples/angular/src/app/hello-world,examples/angular/src/app/home,examples/angular/src/app/todos,examples/angular/src/app/todos/reducers,examples/angular/src/assets,examples/angular/src/lib/shorten,examples/angular/src/shared/material,examples/angular/tools,examples/angular_bazel_architect,examples/angular_bazel_architect/projects/frontend-lib,examples/app,examples/app/styles,examples/app/test,examples/closure,examples/create-react-app,examples/from_source,examples/jest,examples/jest/ts,examples/jest/ts/src,examples/jest/ts/test,examples/kotlin,examples/nestjs,examples/nestjs/src,examples/parcel,examples/protobufjs,examples/react_webpack,examples/toolchain,examples/vue,examples/vue/src,examples/vue/src/components/HelloWorld,examples/web_testing,examples/webapp,examples/worker +build --deleted_packages=e2e/bazel_run_chdir,e2e/bazel_run_chdir/subfolder,e2e/fine_grained_symlinks,e2e/linker_disabled_regression,e2e/linker_disabled_regression/subdir,e2e/node_loader_preserve_symlinks,e2e/nodejs_host,e2e/nodejs_image,e2e/nodejs_image/foolib,e2e/packages,e2e/symlinked_node_modules_npm,e2e/symlinked_node_modules_yarn,examples/angular,examples/angular/src,examples/angular/src/app,examples/angular/src/app/hello-world,examples/angular/src/app/home,examples/angular/src/app/todos,examples/angular/src/app/todos/reducers,examples/angular/src/assets,examples/angular/src/lib/shorten,examples/angular/src/shared/material,examples/angular/tools,examples/angular_bazel_architect,examples/angular_bazel_architect/projects/frontend-lib,examples/app,examples/app/styles,examples/app/test,examples/closure,examples/create-react-app,examples/from_source,examples/jest,examples/jest/ts,examples/jest/ts/src,examples/jest/ts/test,examples/kotlin,examples/nestjs,examples/nestjs/src,examples/parcel,examples/protobufjs,examples/react_webpack,examples/toolchain,examples/vue,examples/vue/src,examples/vue/src/components/HelloWorld,examples/web_testing,examples/webapp,examples/worker +query --deleted_packages=e2e/bazel_run_chdir,e2e/bazel_run_chdir/subfolder,e2e/fine_grained_symlinks,e2e/linker_disabled_regression,e2e/linker_disabled_regression/subdir,e2e/node_loader_preserve_symlinks,e2e/nodejs_host,e2e/nodejs_image,e2e/nodejs_image/foolib,e2e/packages,e2e/symlinked_node_modules_npm,e2e/symlinked_node_modules_yarn,examples/angular,examples/angular/src,examples/angular/src/app,examples/angular/src/app/hello-world,examples/angular/src/app/home,examples/angular/src/app/todos,examples/angular/src/app/todos/reducers,examples/angular/src/assets,examples/angular/src/lib/shorten,examples/angular/src/shared/material,examples/angular/tools,examples/angular_bazel_architect,examples/angular_bazel_architect/projects/frontend-lib,examples/app,examples/app/styles,examples/app/test,examples/closure,examples/create-react-app,examples/from_source,examples/jest,examples/jest/ts,examples/jest/ts/src,examples/jest/ts/test,examples/kotlin,examples/nestjs,examples/nestjs/src,examples/parcel,examples/protobufjs,examples/react_webpack,examples/toolchain,examples/vue,examples/vue/src,examples/vue/src/components/HelloWorld,examples/web_testing,examples/webapp,examples/worker # Mock versioning command to test the --stamp behavior build --workspace_status_command="echo BUILD_SCM_VERSION 1.2.3"
diff --git a/.gitattributes b/.gitattributes index 987d7d9..b71f037 100644 --- a/.gitattributes +++ b/.gitattributes
@@ -1,4 +1,3 @@ docs/Built-ins.md linguist-generated=true docs/Providers.md linguist-generated=true -docs/Rollup.md linguist-generated=true docs/TypeScript.md linguist-generated=true
diff --git a/.github/BUILD.bazel b/.github/BUILD.bazel index e1c2ea3..f782e51 100644 --- a/.github/BUILD.bazel +++ b/.github/BUILD.bazel
@@ -8,7 +8,6 @@ # do not sort owners = [ "//:OWNERS", - "//packages/rollup:OWNERS", "//examples:OWNERS.examples_jest", "//examples:OWNERS.examples_nestjs", "//examples:OWNERS.examples_angular",
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 9bc380e..2a25941 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS
@@ -3,7 +3,6 @@ # yarn update-codeowners * @mattem @gregmagolan @alexeagle -/packages/rollup/** @jbedard @alexeagle @gregmagolan @mattem /examples/jest/** @mrmeku @alexeagle @gregmagolan @mattem /examples/nestjs/** @zachgrayio @zMotivat0r @rayman1104 @siberex @alexeagle @gregmagolan @mattem /examples/angular/** @alan-agius4 @jbedard @alexeagle @gregmagolan @mattem
diff --git a/docs/BUILD.bazel b/docs/BUILD.bazel index 6006933..5b7134e 100644 --- a/docs/BUILD.bazel +++ b/docs/BUILD.bazel
@@ -63,7 +63,6 @@ "Built-ins": "//docs:builtins.md_", "Core": "//docs:core.md_", "Providers": "//docs:providers.md_", - "Rollup": "//packages/rollup:README.md", "TypeScript": "//packages/typescript:README.md", }
diff --git a/docs/Built-ins.md b/docs/Built-ins.md index 18eff1a..95e6e12 100755 --- a/docs/Built-ins.md +++ b/docs/Built-ins.md
@@ -1699,72 +1699,6 @@ -## generated_file_test - -**USAGE** - -<pre> -generated_file_test(<a href="#generated_file_test-name">name</a>, <a href="#generated_file_test-generated">generated</a>, <a href="#generated_file_test-src">src</a>, <a href="#generated_file_test-substring_search">substring_search</a>, <a href="#generated_file_test-src_dbg">src_dbg</a>, <a href="#generated_file_test-visibility">visibility</a>, <a href="#generated_file_test-kwargs">kwargs</a>) -</pre> - -Tests that a file generated by Bazel has identical content to a file in the workspace. - -This is useful for testing, where a "snapshot" or "golden" file is checked in, -so that you can code review changes to the generated output. - -Note, for binary files you can just use the `diff_test` rule from bazel-skylib. -See https://github.com/bazelbuild/bazel-skylib/blob/main/docs/diff_test_doc.md -and https://blog.aspect.dev/bazel-can-write-to-the-source-folder - - -**PARAMETERS** - - -<h4 id="generated_file_test-name">name</h4> - -Name of the rule. - - - -<h4 id="generated_file_test-generated">generated</h4> - -a Label of the output file generated by another rule - - - -<h4 id="generated_file_test-src">src</h4> - -Label of the source file in the workspace - - - -<h4 id="generated_file_test-substring_search">substring_search</h4> - -When true, creates a test that will fail only if the golden file is not found -anywhere within the generated file. Note that the .update rule is not generated in substring mode. - -Defaults to `False` - -<h4 id="generated_file_test-src_dbg">src_dbg</h4> - -if the build uses `--compilation_mode dbg` then some rules will produce different output. -In this case you can specify what the dbg version of the output should look like - -Defaults to `None` - -<h4 id="generated_file_test-visibility">visibility</h4> - -visibility for both test target & update target - -Defaults to `None` - -<h4 id="generated_file_test-kwargs">kwargs</h4> - -extra arguments passed to the underlying nodejs_test - - - - ## js_library **USAGE**
diff --git a/docs/Rollup.md b/docs/Rollup.md deleted file mode 100755 index 1c089bf..0000000 --- a/docs/Rollup.md +++ /dev/null
@@ -1,408 +0,0 @@ -<!-- ********************* - DO NOT EDIT THIS FILE - It is a generated build output from Stardoc. - Instead you must edit the .bzl file where the rules are declared, - or possibly a markdown file next to the .bzl file - ********************* --> - -# Rollup rules for Bazel - -The Rollup rules run the [rollup.js](https://rollupjs.org/) bundler with Bazel. - -## Installation - -Add the `@bazel/rollup` npm package to your `devDependencies` in `package.json`. (`rollup` itself should also be included in `devDependencies`, unless you plan on providing it via a custom target.) - -### Installing with user-managed dependencies - -If you didn't use the `yarn_install` or `npm_install` rule, you'll have to declare a rule in your root `BUILD.bazel` file to execute rollup: - -```python -# Create a rollup rule to use in rollup_bundle#rollup_bin -# attribute when using user-managed dependencies -nodejs_binary( - name = "rollup_bin", - entry_point = "//:node_modules/rollup/bin/rollup", - # Point bazel to your node_modules to find the entry point - data = ["//:node_modules"], -) -``` - -## Usage - -The `rollup_bundle` rule is used to invoke Rollup on some JavaScript inputs. -The API docs appear [below](#rollup_bundle). - -Typical example: -```python -load("@npm//@bazel/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "bundle", - srcs = ["dependency.js"], - entry_point = "input.js", - config_file = "rollup.config.js", -) -``` - -Note that the command-line options set by Bazel override what appears in the rollup config file. -This means that typically a single `rollup.config.js` can contain settings for your whole repo, -and multiple `rollup_bundle` rules can share the configuration. - -Thus, setting options that Bazel controls will have no effect, e.g. - -```javascript -module.exports = { - output: { file: 'this_is_ignored.js' }, -} -``` - -### Output types - -You must determine ahead of time whether Rollup will write a single file or a directory. -Rollup's CLI has the same behavior, forcing you to pick `--output.file` or `--output.dir`. - -Writing a directory is used when you have dynamic imports which cause code-splitting, or if you -provide multiple entry points. Use the `output_dir` attribute to specify that you want a -directory output. - -Each `rollup_bundle` rule produces only one output by running the rollup CLI a single time. -To get multiple output formats, you can wrap the rule with a macro or list comprehension, e.g. - -```python -[ - rollup_bundle( - name = "bundle.%s" % format, - entry_point = "foo.js", - format = format, - ) - for format in [ - "cjs", - "umd", - ] -] -``` - -This will produce one output per requested format. - -### Stamping - -You can stamp the current version control info into the output by writing some code in your rollup config. -See the [stamping documentation](stamping). - -By passing the `--stamp` option to Bazel, two additional input files will be readable by Rollup. - -1. The variable `bazel_version_file` will point to `bazel-out/volatile-status.txt` which contains -statuses that change frequently; such changes do not cause a re-build of the rollup_bundle. -2. The variable `bazel_info_file` will point to `bazel-out/stable-status.txt` file which contains -statuses that stay the same; any changed values will cause rollup_bundle to rebuild. - -Both `bazel_version_file` and `bazel_info_file` will be `undefined` if the build is run without `--stamp`. - -> Note that under `--stamp`, only the bundle is re-built, but not the compilation steps that produced the inputs. -> This avoids a slow cascading re-build of a whole tree of actions. - -To use these files, you write JS code in your `rollup.config.js` to read from the status files and parse the lines. -Each line is a space-separated key/value pair. - -```javascript -/** -* The status files are expected to look like -* BUILD_SCM_HASH 83c699db39cfd74526cdf9bebb75aa6f122908bb -* BUILD_SCM_LOCAL_CHANGES true -* STABLE_BUILD_SCM_VERSION 6.0.0-beta.6+12.sha-83c699d.with-local-changes -* BUILD_TIMESTAMP 1520021990506 -* -* Parsing regex is created based on Bazel's documentation describing the status file schema: -* The key names can be anything but they may only use upper case letters and underscores. The -* first space after the key name separates it from the value. The value is the rest of the line -* (including additional whitespaces). -* -* @param {string} p the path to the status file -* @returns a two-dimensional array of key/value pairs -*/ -function parseStatusFile(p) { - if (!p) return []; - const results = {}; - const statusFile = require('fs').readFileSync(p, {encoding: 'utf-8'}); - for (const match of ` -${statusFile}`.matchAll(/^([A-Z_]+) (.*)/gm)) { - // Lines which go unmatched define an index value of `0` and should be skipped. - if (match.index === 0) { - continue; - } - results[match[1]] = match[2]; - } - return results; -} - -// This undefined variable will be replaced with the full path during the build. -const statuses = parseStatusFile(bazel_version_file); -// Parse the stamp file produced by Bazel from the version control system -let version = '<unknown>'; -// Don't assume BUILD_SCM_VERSION exists -if (statuses['BUILD_SCM_VERSION']) { - version = 'v' + statuses['BUILD_SCM_VERSION']; - if (DEBUG) { - version += '_debug'; - } -} -``` - -### Debug and Opt builds - -When you use `--compilation_mode=dbg`, Bazel produces a distinct output-tree in `bazel-out/[arch]-dbg/bin`. -Code in your `rollup.config.js` can look in the environment to detect if a debug build is being performed, -and include extra developer information in the bundle that you wouldn't normally ship to production. - -Similarly, `--compilation_mode=opt` is Bazel's signal to perform extra optimizations. -You could use this value to perform extra production-only optimizations. - -For example you could define a constant for enabling Debug: - -```javascript -const DEBUG = process.env['COMPILATION_MODE'] === 'dbg'; -``` - -and configure Rollup differently when `DEBUG` is `true` or `false`. - -### Increasing Heap memory for rollup - -The `rollup_bin` attribute allows you to customize the rollup.js program we execute, -so you can use `nodejs_binary` to construct your own. - -> You can always call `bazel query --output=build [default rollup_bin]` to see what -> the default definition looks like, then copy-paste from there to be sure yours -> matches. - -```python -nodejs_binary( - name = "rollup_more_mem", - data = ["@npm//rollup:rollup"], - entry_point = "@npm//:node_modules/rollup/dist/bin/rollup", - templated_args = [ - "--node_options=--max-old-space-size=<SOME_SIZE>", - ], -) - -rollup_bundle( - ... - rollup_bin = ":rollup_more_mem", -) -``` - - -## rollup_bundle - -**USAGE** - -<pre> -rollup_bundle(<a href="#rollup_bundle-name">name</a>, <a href="#rollup_bundle-args">args</a>, <a href="#rollup_bundle-config_file">config_file</a>, <a href="#rollup_bundle-deps">deps</a>, <a href="#rollup_bundle-entry_point">entry_point</a>, <a href="#rollup_bundle-entry_points">entry_points</a>, <a href="#rollup_bundle-format">format</a>, <a href="#rollup_bundle-link_workspace_root">link_workspace_root</a>, - <a href="#rollup_bundle-output_dir">output_dir</a>, <a href="#rollup_bundle-rollup_bin">rollup_bin</a>, <a href="#rollup_bundle-rollup_worker_bin">rollup_worker_bin</a>, <a href="#rollup_bundle-silent">silent</a>, <a href="#rollup_bundle-silent_on_success">silent_on_success</a>, <a href="#rollup_bundle-sourcemap">sourcemap</a>, <a href="#rollup_bundle-srcs">srcs</a>, - <a href="#rollup_bundle-stamp">stamp</a>, <a href="#rollup_bundle-supports_workers">supports_workers</a>) -</pre> - -Runs the rollup.js CLI under Bazel. - -**ATTRIBUTES** - - -<h4 id="rollup_bundle-name">name</h4> - -(*<a href="https://bazel.build/docs/build-ref.html#name">Name</a>, mandatory*): A unique name for this target. - - -<h4 id="rollup_bundle-args">args</h4> - -(*List of strings*): Command line arguments to pass to Rollup. Can be used to override config file settings. - -These argument passed on the command line before arguments that are added by the rule. -Run `bazel` with `--subcommands` to see what Rollup CLI command line was invoked. - -See the <a href="https://rollupjs.org/guide/en/#command-line-flags">Rollup CLI docs</a> for a complete list of supported arguments. - -Defaults to `[]` - -<h4 id="rollup_bundle-config_file">config_file</h4> - -(*<a href="https://bazel.build/docs/build-ref.html#labels">Label</a>*): A `rollup.config.js` file - -Passed to the `--config` option, see [the config doc](https://rollupjs.org/guide/en/#configuration-files) - -If not set, a default basic Rollup config is used. - -Defaults to `@npm//@bazel/rollup:rollup.config.js` - -<h4 id="rollup_bundle-deps">deps</h4> - -(*<a href="https://bazel.build/docs/build-ref.html#labels">List of labels</a>*): Other libraries that are required by the code, or by the rollup.config.js - -Defaults to `[]` - -<h4 id="rollup_bundle-entry_point">entry_point</h4> - -(*<a href="https://bazel.build/docs/build-ref.html#labels">Label</a>*): The bundle's entry point (e.g. your main.js or app.js or index.js). - -This is just a shortcut for the `entry_points` attribute with a single output chunk named the same as the rule. - -For example, these are equivalent: - -```python -rollup_bundle( - name = "bundle", - entry_point = "index.js", -) -``` - -```python -rollup_bundle( - name = "bundle", - entry_points = { - "index.js": "bundle" - } -) -``` - -If `rollup_bundle` is used on a `ts_project`, the `rollup_bundle` rule handles selecting the correct outputs from `ts_project`. -In this case, `entry_point` can be specified as the `.ts` file and `rollup_bundle` will handle the mapping to the `.mjs` output file. - -For example: - -```python -ts_project( - name = "foo", - srcs = [ - "foo.ts", - "index.ts", - ], -) - -rollup_bundle( - name = "bundle", - deps = [ "foo" ], - entry_point = "index.ts", -) -``` - -Defaults to `None` - -<h4 id="rollup_bundle-entry_points">entry_points</h4> - -(*<a href="https://bazel.build/docs/skylark/lib/dict.html">Dictionary: Label -> String</a>*): The bundle's entry points (e.g. your main.js or app.js or index.js). - -Passed to the [`--input` option](https://github.com/rollup/rollup/blob/master/docs/999-big-list-of-options.md#input) in Rollup. - -Keys in this dictionary are labels pointing to .js entry point files. -Values are the name to be given to the corresponding output chunk. - -Either this attribute or `entry_point` must be specified, but not both. - -Defaults to `{}` - -<h4 id="rollup_bundle-format">format</h4> - -(*String*): Specifies the format of the generated bundle. One of the following: - -- `amd`: Asynchronous Module Definition, used with module loaders like RequireJS -- `cjs`: CommonJS, suitable for Node and other bundlers -- `esm`: Keep the bundle as an ES module file, suitable for other bundlers and inclusion as a `<script type=module>` tag in modern browsers -- `iife`: A self-executing function, suitable for inclusion as a `<script>` tag. (If you want to create a bundle for your application, you probably want to use this.) -- `umd`: Universal Module Definition, works as amd, cjs and iife all in one -- `system`: Native format of the SystemJS loader - -Defaults to `"esm"` - -<h4 id="rollup_bundle-link_workspace_root">link_workspace_root</h4> - -(*Boolean*): Link the workspace root to the bin_dir to support absolute requires like 'my_wksp/path/to/file'. -If source files need to be required then they can be copied to the bin_dir with copy_to_bin. - -Defaults to `False` - -<h4 id="rollup_bundle-output_dir">output_dir</h4> - -(*Boolean*): Whether to produce a directory output. - -We will use the [`--output.dir` option](https://github.com/rollup/rollup/blob/master/docs/999-big-list-of-options.md#outputdir) in rollup -rather than `--output.file`. - -If the program produces multiple chunks, you must specify this attribute. -Otherwise, the outputs are assumed to be a single file. - -Defaults to `False` - -<h4 id="rollup_bundle-rollup_bin">rollup_bin</h4> - -(*<a href="https://bazel.build/docs/build-ref.html#labels">Label</a>*): Target that executes the rollup binary - -Defaults to `@npm//rollup/bin:rollup` - -<h4 id="rollup_bundle-rollup_worker_bin">rollup_worker_bin</h4> - -(*<a href="https://bazel.build/docs/build-ref.html#labels">Label</a>*): Internal use only - -Defaults to `@npm//@bazel/rollup/bin:rollup-worker` - -<h4 id="rollup_bundle-silent">silent</h4> - -(*Boolean*): Whether to execute the rollup binary with the --silent flag, defaults to False. - -Using --silent can cause rollup to [ignore errors/warnings](https://github.com/rollup/rollup/blob/master/docs/999-big-list-of-options.md#onwarn) -which are only surfaced via logging. Since bazel expects printing nothing on success, setting silent to True -is a more Bazel-idiomatic experience, however could cause rollup to drop important warnings. - -Defaults to `False` - -<h4 id="rollup_bundle-silent_on_success">silent_on_success</h4> - -(*Boolean*): Even stronger than --silent, defaults to False. - -Since the build still emits some texted, even when passed --silent, this uses the same flag as npm_package_bin to -supress all output on sucess. - -Defaults to `False` - -<h4 id="rollup_bundle-sourcemap">sourcemap</h4> - -(*String*): Whether to produce sourcemaps. - -Passed to the [`--sourcemap` option](https://github.com/rollup/rollup/blob/master/docs/999-big-list-of-options.md#outputsourcemap") in Rollup - -Defaults to `"inline"` - -<h4 id="rollup_bundle-srcs">srcs</h4> - -(*<a href="https://bazel.build/docs/build-ref.html#labels">List of labels</a>*): Non-entry point JavaScript source files from the workspace. - -You must not repeat file(s) passed to entry_point/entry_points. - -Defaults to `[]` - -<h4 id="rollup_bundle-stamp">stamp</h4> - -(*<a href="https://bazel.build/docs/build-ref.html#labels">Label</a>*): Whether to encode build information into the output. Possible values: - - `@rules_nodejs//nodejs/stamp:always`: - Always stamp the build information into the output, even in [--nostamp][stamp] builds. - This setting should be avoided, since it potentially causes cache misses remote caching for - any downstream actions that depend on it. - - `@rules_nodejs//nodejs/stamp:never`: - Always replace build information by constant values. This gives good build result caching. - - `@rules_nodejs//nodejs/stamp:use_stamp_flag`: - Embedding of build information is controlled by the [--[no]stamp][stamp] flag. - Stamped binaries are not rebuilt unless their dependencies change. - [stamp]: https://docs.bazel.build/versions/main/user-manual.html#flag--stamp The dependencies of this attribute must provide: StampSettingInfo - - -Defaults to `@rules_nodejs//nodejs/stamp:use_stamp_flag` - -<h4 id="rollup_bundle-supports_workers">supports_workers</h4> - -(*Boolean*): Experimental! Use only with caution. - -Allows you to enable the Bazel Worker strategy for this library. -When enabled, this rule invokes the "rollup_worker_bin" -worker aware binary rather than "rollup_bin". - -Defaults to `False` - -
diff --git a/e2e/BUILD.bazel b/e2e/BUILD.bazel index 45e73e5..68101b4 100644 --- a/e2e/BUILD.bazel +++ b/e2e/BUILD.bazel
@@ -67,19 +67,6 @@ tags = ["no-bazelci-windows"], ) -# rollup rules are tested in the e2e_webapp -test_suite( - name = "e2e_rollup", - tests = ["e2e_webapp"], -) - -e2e_integration_test( - name = "e2e_webapp", - npm_packages = { - "//packages/rollup:npm_package": "@bazel/rollup", - }, -) - e2e_integration_test( name = "e2e_bazel_run_chdir", bazel_commands = [
diff --git a/e2e/webapp/.bazelrc b/e2e/webapp/.bazelrc deleted file mode 100644 index 3431057..0000000 --- a/e2e/webapp/.bazelrc +++ /dev/null
@@ -1 +0,0 @@ -import %workspace%/../../common.bazelrc
diff --git a/e2e/webapp/BUILD.bazel b/e2e/webapp/BUILD.bazel deleted file mode 100644 index b78a56b..0000000 --- a/e2e/webapp/BUILD.bazel +++ /dev/null
@@ -1,18 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_test") -load("@npm//@bazel/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "app", - srcs = ["strings.js"], - entry_point = "app.js", - output_dir = True, - # Enable experimental faster builds with Bazel workers - # TODO: re-enable worker mode once fixed in bazel_integration_test - # supports_workers = True, -) - -nodejs_test( - name = "test", - data = ["app"], - entry_point = ":test.js", -)
diff --git a/e2e/webapp/WORKSPACE b/e2e/webapp/WORKSPACE deleted file mode 100644 index 74811fb..0000000 --- a/e2e/webapp/WORKSPACE +++ /dev/null
@@ -1,35 +0,0 @@ -# Copyright 2018 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -workspace(name = "e2e_webapp") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") - -http_archive( - name = "build_bazel_rules_nodejs", - sha256 = "94070eff79305be05b7699207fbac5d2608054dd53e6109f7d00d923919ff45a", - urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.8.2/rules_nodejs-5.8.2.tar.gz"], -) - -load("@build_bazel_rules_nodejs//:repositories.bzl", "build_bazel_rules_nodejs_dependencies") - -build_bazel_rules_nodejs_dependencies() - -load("@build_bazel_rules_nodejs//:index.bzl", "yarn_install") - -yarn_install( - name = "npm", - package_json = "//:package.json", - yarn_lock = "//:yarn.lock", -)
diff --git a/e2e/webapp/app.js b/e2e/webapp/app.js deleted file mode 100644 index 1e29b6e..0000000 --- a/e2e/webapp/app.js +++ /dev/null
@@ -1 +0,0 @@ -import('./strings').then(m => {const msg = document.createElement('span'); msg.innerText = m.hello(); document.body.appendChild(msg);}); \ No newline at end of file
diff --git a/e2e/webapp/package.json b/e2e/webapp/package.json deleted file mode 100644 index e3c1421..0000000 --- a/e2e/webapp/package.json +++ /dev/null
@@ -1,13 +0,0 @@ -{ - "name": "e2e-terser", - "private": true, - "devDependencies": { - "@bazel/rollup": "^5.8.1", - "@bazel/terser": "^5.8.1", - "rollup": "2.3.0", - "terser": "4.3.1" - }, - "scripts": { - "test": "bazel test ..." - } -}
diff --git a/e2e/webapp/strings.js b/e2e/webapp/strings.js deleted file mode 100644 index c0bc83e..0000000 --- a/e2e/webapp/strings.js +++ /dev/null
@@ -1,3 +0,0 @@ -export function hello() { - return 'Hello World'; -}
diff --git a/e2e/webapp/test.js b/e2e/webapp/test.js deleted file mode 100644 index 14b0c57..0000000 --- a/e2e/webapp/test.js +++ /dev/null
@@ -1,7 +0,0 @@ -const fs = require('fs'); -const runfiles = require(process.env['BAZEL_NODE_RUNFILES_HELPER']); -const content = fs.readFileSync(runfiles.resolve('e2e_webapp/out.min/app.js'), 'utf-8'); -if (content.indexOf('import("./strings') < 0) { - console.error(content); - process.exitCode = 1; -}
diff --git a/e2e/webapp/yarn.lock b/e2e/webapp/yarn.lock deleted file mode 100644 index c51bfb0..0000000 --- a/e2e/webapp/yarn.lock +++ /dev/null
@@ -1,71 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@bazel/rollup@^5.8.1": - version "5.8.1" - resolved "https://registry.yarnpkg.com/@bazel/rollup/-/rollup-5.8.1.tgz#ee876c35595b456f700d258385412e4f0dd57c15" - integrity sha512-Ys+UWbRp1TY2j+z15N+SZgID/nuqAtJTgJDsz0NZVjm8F8KzmgXxLDnBb/cUKFVk83pNOAi84G/bq1tINjMSNA== - dependencies: - "@bazel/worker" "5.8.1" - -"@bazel/terser@^5.8.1": - version "5.8.1" - resolved "https://registry.yarnpkg.com/@bazel/terser/-/terser-5.8.1.tgz#729a0ec6dcc83e99c4f6d3f2bebb0ff254c10c48" - integrity sha512-TPjSDhw1pSZt9P2hd/22IJwl8KCZiJL+u2gB5mghBTCFDVdC5Dgsx135pFtvlqc6LjjOvd3s6dzcQr0YJo2HSg== - -"@bazel/worker@5.8.1": - version "5.8.1" - resolved "https://registry.yarnpkg.com/@bazel/worker/-/worker-5.8.1.tgz#65af7a70dd2f1aaedd6c19330abd9a198f96e7b2" - integrity sha512-GMyZSNW3F34f9GjbJqvs1aHyed5BNrNeiDzNJhC1fIizo/UeBM21oBBONIYLBDoBtq936U85VyPZ76JaP/83hw== - dependencies: - google-protobuf "^3.6.1" - -buffer-from@^1.0.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" - integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== - -commander@^2.20.0: - version "2.20.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.0.tgz#d58bb2b5c1ee8f87b0d340027e9e94e222c5a422" - integrity sha512-7j2y+40w61zy6YC2iRNpUe/NwhNyoXrYpHMrSunaMG64nRnaf96zO/KMQR4OyN/UnE5KLyEBnKHd4aG3rskjpQ== - -fsevents@~2.1.2: - version "2.1.3" - resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.1.3.tgz#fb738703ae8d2f9fe900c33836ddebee8b97f23e" - integrity sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ== - -google-protobuf@^3.6.1: - version "3.17.3" - resolved "https://registry.yarnpkg.com/google-protobuf/-/google-protobuf-3.17.3.tgz#f87595073545a77946c8f0b67c302c5f7646d700" - integrity sha512-OVPzcSWIAJ+d5yiHyeaLrdufQtrvaBrF4JQg+z8ynTkbO3uFcujqXszTumqg1cGsAsjkWnI+M5B1xZ19yR4Wyg== - -rollup@2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/rollup/-/rollup-2.3.0.tgz#0b9e1c19bea22464958854dae646b8b40d2d3ed5" - integrity sha512-nIq2Z9YwNbEfqTlAXe/tVl8CwUsjX/8Q5Jxlx+JRoYCu5keKLc6k0zyt11sM6WtCDxhmmJEIosFy9y26ZFRx6w== - optionalDependencies: - fsevents "~2.1.2" - -source-map-support@~0.5.12: - version "0.5.13" - resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.13.tgz#31b24a9c2e73c2de85066c0feb7d44767ed52932" - integrity sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w== - dependencies: - buffer-from "^1.0.0" - source-map "^0.6.0" - -source-map@^0.6.0, source-map@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" - integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== - -terser@4.3.1: - version "4.3.1" - resolved "https://registry.yarnpkg.com/terser/-/terser-4.3.1.tgz#09820bcb3398299c4b48d9a86aefc65127d0ed65" - integrity sha512-pnzH6dnFEsR2aa2SJaKb1uSCl3QmIsJ8dEkj0Fky+2AwMMcC9doMqLOQIH6wVTEKaVfKVvLSk5qxPBEZT9mywg== - dependencies: - commander "^2.20.0" - source-map "~0.6.1" - source-map-support "~0.5.12"
diff --git a/examples/BUILD.bazel b/examples/BUILD.bazel index 107afe8..62320ed 100644 --- a/examples/BUILD.bazel +++ b/examples/BUILD.bazel
@@ -18,7 +18,6 @@ name = "examples_angular", timeout = "long", npm_packages = { - "//packages/rollup:npm_package": "@bazel/rollup", "//packages/typescript:npm_package": "@bazel/typescript", }, owners = [ @@ -64,7 +63,6 @@ example_integration_test( name = "examples_app", npm_packages = { - "//packages/rollup:npm_package": "@bazel/rollup", "//packages/typescript:npm_package": "@bazel/typescript", }, ) @@ -108,7 +106,6 @@ example_integration_test( name = "examples_kotlin", npm_packages = { - "//packages/rollup:npm_package": "@bazel/rollup", }, tags = [ # Bintray was removed from the internet, and the version of @@ -143,7 +140,6 @@ "test ... --enable_runfiles", ], npm_packages = { - "//packages/rollup:npm_package": "@bazel/rollup", "//packages/typescript:npm_package": "@bazel/typescript", }, )
diff --git a/index.for_docs.bzl b/index.for_docs.bzl index 50b0181..63cc625 100644 --- a/index.for_docs.bzl +++ b/index.for_docs.bzl
@@ -25,7 +25,6 @@ load("//internal/common:copy_to_bin.bzl", _copy_to_bin = "copy_to_bin") load("//internal/common:params_file.bzl", _params_file = "params_file") -load("//internal/generated_file_test:generated_file_test.bzl", _generated_file_test = "generated_file_test") load("//internal/js_library:js_library.bzl", _js_library = "js_library") load("//internal/node:node.bzl", _nodejs_binary = "nodejs_binary", _nodejs_test = "nodejs_test") load("//internal/node:npm_package_bin.bzl", _npm_bin = "npm_package_bin") @@ -42,5 +41,4 @@ yarn_install = _yarn_install npm_package_bin = _npm_bin pkg_web = _pkg_web -generated_file_test = _generated_file_test js_library = _js_library
diff --git a/internal/generated_file_test/BUILD.bazel b/internal/generated_file_test/BUILD.bazel index 59a2f74..102171b 100644 --- a/internal/generated_file_test/BUILD.bazel +++ b/internal/generated_file_test/BUILD.bazel
@@ -1,5 +1,5 @@ load("@bazel_skylib//:bzl_library.bzl", "bzl_library") -load("//packages/rollup:index.bzl", "rollup_bundle") +load("//internal/common:copy_to_bin.bzl", "copy_to_bin") load("@bazel_skylib//rules:write_file.bzl", "write_file") package(default_visibility = ["//visibility:public"]) @@ -29,14 +29,9 @@ ], ) -rollup_bundle( +copy_to_bin( name = "bundle", - config_file = "rollup.config.js", - entry_point = "bin.js", - sourcemap = "hidden", - deps = [ - "@npm//@rollup/plugin-commonjs", - "@npm//@rollup/plugin-node-resolve", - "@npm//unidiff", - ], + srcs = ["bundle.js"], ) + +exports_files(["bundle.js"])
diff --git a/internal/generated_file_test/bundle.js b/internal/generated_file_test/bundle.js new file mode 100644 index 0000000..a7a7968 --- /dev/null +++ b/internal/generated_file_test/bundle.js
@@ -0,0 +1,1680 @@ +function createCommonjsModule(fn) { + var module = { exports: {} }; + return fn(module, module.exports), module.exports; +} + +/*istanbul ignore start*/ + + +var _default$1 = /*istanbul ignore end*/Diff; +function Diff() {} + +Diff.prototype = { /*istanbul ignore start*/ + /*istanbul ignore end*/diff: function diff(oldString, newString) { + /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + var callback = options.callback; + if (typeof options === 'function') { + callback = options; + options = {}; + } + this.options = options; + + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } + + // Allow subclasses to massage the input prior to running + oldString = this.castInput(oldString); + newString = this.castInput(newString); + + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ newPos: -1, components: [] }]; + + // Seed editLength = 0, i.e. the content starts with the same values + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ value: newString.join(''), count: newString.length }]); + } + + // Main worker method. checks all permutations of a given edit length for acceptance. + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } + + // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); + + // If we have hit the end of both strings, then we are done + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } + + // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + if (ret) { + return ret; + } + } + } + }, + /*istanbul ignore start*/ /*istanbul ignore end*/pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { count: last.count + 1, added: added, removed: removed }; + } else { + components.push({ count: 1, added: added, removed: removed }); + } + }, + /*istanbul ignore start*/ /*istanbul ignore end*/extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ count: commonCount }); + } + + basePath.newPos = newPos; + return oldPos; + }, + /*istanbul ignore start*/ /*istanbul ignore end*/equals: function equals(left, right) { + return left === right; + }, + /*istanbul ignore start*/ /*istanbul ignore end*/removeEmpty: function removeEmpty(array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + }, + /*istanbul ignore start*/ /*istanbul ignore end*/castInput: function castInput(value) { + return value; + }, + /*istanbul ignore start*/ /*istanbul ignore end*/tokenize: function tokenize(value) { + return value.split(''); + } +}; + +function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + + component.value = value.join(''); + } else { + component.value = newString.slice(newPos, newPos + component.count).join(''); + } + newPos += component.count; + + // Common case + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = oldString.slice(oldPos, oldPos + component.count).join(''); + oldPos += component.count; + + // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } + + // Special case handle for when one terminal is ignored. For this case we merge the + // terminal into the prior string and drop the change. + var lastComponent = components[componentLen - 1]; + if (componentLen > 1 && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; +} + +function clonePath(path) { + return { newPos: path.newPos, components: path.components.slice(0) }; +} + + +var base = /*#__PURE__*/Object.defineProperty({ + default: _default$1 +}, '__esModule', {value: true}); + +/*istanbul ignore start*/ + +var character = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; +exports.characterDiff = undefined; +exports. /*istanbul ignore end*/diffChars = diffChars; + + + +/*istanbul ignore start*/ +var _base2 = _interopRequireDefault(base); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/var characterDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/characterDiff = new /*istanbul ignore start*/_base2.default() /*istanbul ignore end*/; +function diffChars(oldStr, newStr, callback) { + return characterDiff.diff(oldStr, newStr, callback); +} +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2NoYXJhY3Rlci5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7O2dDQUdnQjs7QUFIaEI7Ozs7Ozs7dUJBRU8sSUFBTSx5RkFBZ0IscUVBQWhCO0FBQ04sU0FBUyxTQUFULENBQW1CLE1BQW5CLEVBQTJCLE1BQTNCLEVBQW1DLFFBQW5DLEVBQTZDO0FBQUUsU0FBTyxjQUFjLElBQWQsQ0FBbUIsTUFBbkIsRUFBMkIsTUFBM0IsRUFBbUMsUUFBbkMsQ0FBUCxDQUFGO0NBQTdDIiwiZmlsZSI6ImNoYXJhY3Rlci5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cbmV4cG9ydCBjb25zdCBjaGFyYWN0ZXJEaWZmID0gbmV3IERpZmYoKTtcbmV4cG9ydCBmdW5jdGlvbiBkaWZmQ2hhcnMob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKSB7IHJldHVybiBjaGFyYWN0ZXJEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKTsgfVxuIl19 +}); + +/*istanbul ignore start*/ + + +var generateOptions_1 = generateOptions; +function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + return defaults; +} + + +var params = /*#__PURE__*/Object.defineProperty({ + generateOptions: generateOptions_1 +}, '__esModule', {value: true}); + +/*istanbul ignore start*/ + +var word = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; +exports.wordDiff = undefined; +exports. /*istanbul ignore end*/diffWords = diffWords; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = diffWordsWithSpace; + + + +/*istanbul ignore start*/ +var _base2 = _interopRequireDefault(base); + +/*istanbul ignore end*/ + + +/*istanbul ignore start*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ + +// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode +// +// Ranges and exceptions: +// Latin-1 Supplement, 0080–00FF +// - U+00D7 × Multiplication sign +// - U+00F7 ÷ Division sign +// Latin Extended-A, 0100–017F +// Latin Extended-B, 0180–024F +// IPA Extensions, 0250–02AF +// Spacing Modifier Letters, 02B0–02FF +// - U+02C7 ˇ ˇ Caron +// - U+02D8 ˘ ˘ Breve +// - U+02D9 ˙ ˙ Dot Above +// - U+02DA ˚ ˚ Ring Above +// - U+02DB ˛ ˛ Ogonek +// - U+02DC ˜ ˜ Small Tilde +// - U+02DD ˝ ˝ Double Acute Accent +// Latin Extended Additional, 1E00–1EFF +var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; + +var reWhitespace = /\S/; + +var wordDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/wordDiff = new /*istanbul ignore start*/_base2.default() /*istanbul ignore end*/; +wordDiff.equals = function (left, right) { + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); +}; +wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|\b)/); + + // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; +}; + +function diffWords(oldStr, newStr, callback) { + var options = /*istanbul ignore start*/(0, params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true }); + return wordDiff.diff(oldStr, newStr, options); +} +function diffWordsWithSpace(oldStr, newStr, callback) { + return wordDiff.diff(oldStr, newStr, callback); +} +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3dvcmQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7OztnQ0ErQ2dCO3lEQUlBOztBQW5EaEI7Ozs7OztBQUNBOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBb0JBLElBQU0sb0JBQW9CLCtEQUFwQjs7QUFFTixJQUFNLGVBQWUsSUFBZjs7QUFFQyxJQUFNLCtFQUFXLHFFQUFYO0FBQ2IsU0FBUyxNQUFULEdBQWtCLFVBQVMsSUFBVCxFQUFlLEtBQWYsRUFBc0I7QUFDdEMsU0FBTyxTQUFTLEtBQVQsSUFBbUIsS0FBSyxPQUFMLENBQWEsZ0JBQWIsSUFBaUMsQ0FBQyxhQUFhLElBQWIsQ0FBa0IsSUFBbEIsQ0FBRCxJQUE0QixDQUFDLGFBQWEsSUFBYixDQUFrQixLQUFsQixDQUFELENBRGpEO0NBQXRCO0FBR2xCLFNBQVMsUUFBVCxHQUFvQixVQUFTLEtBQVQsRUFBZ0I7QUFDbEMsTUFBSSxTQUFTLE1BQU0sS0FBTixDQUFZLFVBQVosQ0FBVDs7O0FBRDhCLE9BSTdCLElBQUksSUFBSSxDQUFKLEVBQU8sSUFBSSxPQUFPLE1BQVAsR0FBZ0IsQ0FBaEIsRUFBbUIsR0FBdkMsRUFBNEM7O0FBRTFDLFFBQUksQ0FBQyxPQUFPLElBQUksQ0FBSixDQUFSLElBQWtCLE9BQU8sSUFBSSxDQUFKLENBQXpCLElBQ0ssa0JBQWtCLElBQWxCLENBQXVCLE9BQU8sQ0FBUCxDQUF2QixDQURMLElBRUssa0JBQWtCLElBQWxCLENBQXVCLE9BQU8sSUFBSSxDQUFKLENBQTlCLENBRkwsRUFFNEM7QUFDOUMsYUFBTyxDQUFQLEtBQWEsT0FBTyxJQUFJLENBQUosQ0FBcEIsQ0FEOEM7QUFFOUMsYUFBTyxNQUFQLENBQWMsSUFBSSxDQUFKLEVBQU8sQ0FBckIsRUFGOEM7QUFHOUMsVUFIOEM7S0FGaEQ7R0FGRjs7QUFXQSxTQUFPLE1BQVAsQ0Fma0M7Q0FBaEI7O0FBa0JiLFNBQVMsU0FBVCxDQUFtQixNQUFuQixFQUEyQixNQUEzQixFQUFtQyxRQUFuQyxFQUE2QztBQUNsRCxNQUFJLFVBQVUsOEVBQWdCLFFBQWhCLEVBQTBCLEVBQUMsa0JBQWtCLElBQWxCLEVBQTNCLENBQVYsQ0FEOEM7QUFFbEQsU0FBTyxTQUFTLElBQVQsQ0FBYyxNQUFkLEVBQXNCLE1BQXRCLEVBQThCLE9BQTlCLENBQVAsQ0FGa0Q7Q0FBN0M7QUFJQSxTQUFTLGtCQUFULENBQTRCLE1BQTVCLEVBQW9DLE1BQXBDLEVBQTRDLFFBQTVDLEVBQXNEO0FBQzNELFNBQU8sU0FBUyxJQUFULENBQWMsTUFBZCxFQUFzQixNQUF0QixFQUE4QixRQUE5QixDQUFQLENBRDJEO0NBQXREIiwiZmlsZSI6IndvcmQuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuaW1wb3J0IHtnZW5lcmF0ZU9wdGlvbnN9IGZyb20gJy4uL3V0aWwvcGFyYW1zJztcblxuLy8gQmFzZWQgb24gaHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvTGF0aW5fc2NyaXB0X2luX1VuaWNvZGVcbi8vXG4vLyBSYW5nZXMgYW5kIGV4Y2VwdGlvbnM6XG4vLyBMYXRpbi0xIFN1cHBsZW1lbnQsIDAwODDigJMwMEZGXG4vLyAgLSBVKzAwRDcgIMOXIE11bHRpcGxpY2F0aW9uIHNpZ25cbi8vICAtIFUrMDBGNyAgw7cgRGl2aXNpb24gc2lnblxuLy8gTGF0aW4gRXh0ZW5kZWQtQSwgMDEwMOKAkzAxN0Zcbi8vIExhdGluIEV4dGVuZGVkLUIsIDAxODDigJMwMjRGXG4vLyBJUEEgRXh0ZW5zaW9ucywgMDI1MOKAkzAyQUZcbi8vIFNwYWNpbmcgTW9kaWZpZXIgTGV0dGVycywgMDJCMOKAkzAyRkZcbi8vICAtIFUrMDJDNyAgy4cgJiM3MTE7ICBDYXJvblxuLy8gIC0gVSswMkQ4ICDLmCAmIzcyODsgIEJyZXZlXG4vLyAgLSBVKzAyRDkgIMuZICYjNzI5OyAgRG90IEFib3ZlXG4vLyAgLSBVKzAyREEgIMuaICYjNzMwOyAgUmluZyBBYm92ZVxuLy8gIC0gVSswMkRCICDLmyAmIzczMTsgIE9nb25la1xuLy8gIC0gVSswMkRDICDLnCAmIzczMjsgIFNtYWxsIFRpbGRlXG4vLyAgLSBVKzAyREQgIMudICYjNzMzOyAgRG91YmxlIEFjdXRlIEFjY2VudFxuLy8gTGF0aW4gRXh0ZW5kZWQgQWRkaXRpb25hbCwgMUUwMOKAkzFFRkZcbmNvbnN0IGV4dGVuZGVkV29yZENoYXJzID0gL15bYS16QS1aXFx1e0MwfS1cXHV7RkZ9XFx1e0Q4fS1cXHV7RjZ9XFx1e0Y4fS1cXHV7MkM2fVxcdXsyQzh9LVxcdXsyRDd9XFx1ezJERX0tXFx1ezJGRn1cXHV7MUUwMH0tXFx1ezFFRkZ9XSskL3U7XG5cbmNvbnN0IHJlV2hpdGVzcGFjZSA9IC9cXFMvO1xuXG5leHBvcnQgY29uc3Qgd29yZERpZmYgPSBuZXcgRGlmZigpO1xud29yZERpZmYuZXF1YWxzID0gZnVuY3Rpb24obGVmdCwgcmlnaHQpIHtcbiAgcmV0dXJuIGxlZnQgPT09IHJpZ2h0IHx8ICh0aGlzLm9wdGlvbnMuaWdub3JlV2hpdGVzcGFjZSAmJiAhcmVXaGl0ZXNwYWNlLnRlc3QobGVmdCkgJiYgIXJlV2hpdGVzcGFjZS50ZXN0KHJpZ2h0KSk7XG59O1xud29yZERpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICBsZXQgdG9rZW5zID0gdmFsdWUuc3BsaXQoLyhcXHMrfFxcYikvKTtcblxuICAvLyBKb2luIHRoZSBib3VuZGFyeSBzcGxpdHMgdGhhdCB3ZSBkbyBub3QgY29uc2lkZXIgdG8gYmUgYm91bmRhcmllcy4gVGhpcyBpcyBwcmltYXJpbHkgdGhlIGV4dGVuZGVkIExhdGluIGNoYXJhY3RlciBzZXQuXG4gIGZvciAobGV0IGkgPSAwOyBpIDwgdG9rZW5zLmxlbmd0aCAtIDE7IGkrKykge1xuICAgIC8vIElmIHdlIGhhdmUgYW4gZW1wdHkgc3RyaW5nIGluIHRoZSBuZXh0IGZpZWxkIGFuZCB3ZSBoYXZlIG9ubHkgd29yZCBjaGFycyBiZWZvcmUgYW5kIGFmdGVyLCBtZXJnZVxuICAgIGlmICghdG9rZW5zW2kgKyAxXSAmJiB0b2tlbnNbaSArIDJdXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaV0pXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaSArIDJdKSkge1xuICAgICAgdG9rZW5zW2ldICs9IHRva2Vuc1tpICsgMl07XG4gICAgICB0b2tlbnMuc3BsaWNlKGkgKyAxLCAyKTtcbiAgICAgIGktLTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gdG9rZW5zO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3JkcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHtcbiAgbGV0IG9wdGlvbnMgPSBnZW5lcmF0ZU9wdGlvbnMoY2FsbGJhY2ssIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiB3b3JkRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cbmV4cG9ydCBmdW5jdGlvbiBkaWZmV29yZHNXaXRoU3BhY2Uob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKSB7XG4gIHJldHVybiB3b3JkRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7XG59XG4iXX0= +}); + +/*istanbul ignore start*/ + +var line = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; +exports.lineDiff = undefined; +exports. /*istanbul ignore end*/diffLines = diffLines; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = diffTrimmedLines; + + + +/*istanbul ignore start*/ +var _base2 = _interopRequireDefault(base); + +/*istanbul ignore end*/ + + +/*istanbul ignore start*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/var lineDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/lineDiff = new /*istanbul ignore start*/_base2.default() /*istanbul ignore end*/; +lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); + + // Ignore the final empty token that occurs if the string ends with a new line + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } + + // Merge the content and line separators into single tokens + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + retLines.push(line); + } + } + + return retLines; +}; + +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} +function diffTrimmedLines(oldStr, newStr, callback) { + var options = /*istanbul ignore start*/(0, params.generateOptions) /*istanbul ignore end*/(callback, { ignoreWhitespace: true }); + return lineDiff.diff(oldStr, newStr, options); +} +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2xpbmUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7OztnQ0E4QmdCO3lEQUNBOztBQS9CaEI7Ozs7OztBQUNBOzs7Ozt1QkFFTyxJQUFNLCtFQUFXLHFFQUFYO0FBQ2IsU0FBUyxRQUFULEdBQW9CLFVBQVMsS0FBVCxFQUFnQjtBQUNsQyxNQUFJLFdBQVcsRUFBWDtNQUNBLG1CQUFtQixNQUFNLEtBQU4sQ0FBWSxXQUFaLENBQW5COzs7QUFGOEIsTUFLOUIsQ0FBQyxpQkFBaUIsaUJBQWlCLE1BQWpCLEdBQTBCLENBQTFCLENBQWxCLEVBQWdEO0FBQ2xELHFCQUFpQixHQUFqQixHQURrRDtHQUFwRDs7O0FBTGtDLE9BVTdCLElBQUksSUFBSSxDQUFKLEVBQU8sSUFBSSxpQkFBaUIsTUFBakIsRUFBeUIsR0FBN0MsRUFBa0Q7QUFDaEQsUUFBSSxPQUFPLGlCQUFpQixDQUFqQixDQUFQLENBRDRDOztBQUdoRCxRQUFJLElBQUksQ0FBSixJQUFTLENBQUMsS0FBSyxPQUFMLENBQWEsY0FBYixFQUE2QjtBQUN6QyxlQUFTLFNBQVMsTUFBVCxHQUFrQixDQUFsQixDQUFULElBQWlDLElBQWpDLENBRHlDO0tBQTNDLE1BRU87QUFDTCxVQUFJLEtBQUssT0FBTCxDQUFhLGdCQUFiLEVBQStCO0FBQ2pDLGVBQU8sS0FBSyxJQUFMLEVBQVAsQ0FEaUM7T0FBbkM7QUFHQSxlQUFTLElBQVQsQ0FBYyxJQUFkLEVBSks7S0FGUDtHQUhGOztBQWFBLFNBQU8sUUFBUCxDQXZCa0M7Q0FBaEI7O0FBMEJiLFNBQVMsU0FBVCxDQUFtQixNQUFuQixFQUEyQixNQUEzQixFQUFtQyxRQUFuQyxFQUE2QztBQUFFLFNBQU8sU0FBUyxJQUFULENBQWMsTUFBZCxFQUFzQixNQUF0QixFQUE4QixRQUE5QixDQUFQLENBQUY7Q0FBN0M7QUFDQSxTQUFTLGdCQUFULENBQTBCLE1BQTFCLEVBQWtDLE1BQWxDLEVBQTBDLFFBQTFDLEVBQW9EO0FBQ3pELE1BQUksVUFBVSw4RUFBZ0IsUUFBaEIsRUFBMEIsRUFBQyxrQkFBa0IsSUFBbEIsRUFBM0IsQ0FBVixDQURxRDtBQUV6RCxTQUFPLFNBQVMsSUFBVCxDQUFjLE1BQWQsRUFBc0IsTUFBdEIsRUFBOEIsT0FBOUIsQ0FBUCxDQUZ5RDtDQUFwRCIsImZpbGUiOiJsaW5lLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcbmltcG9ydCB7Z2VuZXJhdGVPcHRpb25zfSBmcm9tICcuLi91dGlsL3BhcmFtcyc7XG5cbmV4cG9ydCBjb25zdCBsaW5lRGlmZiA9IG5ldyBEaWZmKCk7XG5saW5lRGlmZi50b2tlbml6ZSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIGxldCByZXRMaW5lcyA9IFtdLFxuICAgICAgbGluZXNBbmROZXdsaW5lcyA9IHZhbHVlLnNwbGl0KC8oXFxufFxcclxcbikvKTtcblxuICAvLyBJZ25vcmUgdGhlIGZpbmFsIGVtcHR5IHRva2VuIHRoYXQgb2NjdXJzIGlmIHRoZSBzdHJpbmcgZW5kcyB3aXRoIGEgbmV3IGxpbmVcbiAgaWYgKCFsaW5lc0FuZE5ld2xpbmVzW2xpbmVzQW5kTmV3bGluZXMubGVuZ3RoIC0gMV0pIHtcbiAgICBsaW5lc0FuZE5ld2xpbmVzLnBvcCgpO1xuICB9XG5cbiAgLy8gTWVyZ2UgdGhlIGNvbnRlbnQgYW5kIGxpbmUgc2VwYXJhdG9ycyBpbnRvIHNpbmdsZSB0b2tlbnNcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBsaW5lc0FuZE5ld2xpbmVzLmxlbmd0aDsgaSsrKSB7XG4gICAgbGV0IGxpbmUgPSBsaW5lc0FuZE5ld2xpbmVzW2ldO1xuXG4gICAgaWYgKGkgJSAyICYmICF0aGlzLm9wdGlvbnMubmV3bGluZUlzVG9rZW4pIHtcbiAgICAgIHJldExpbmVzW3JldExpbmVzLmxlbmd0aCAtIDFdICs9IGxpbmU7XG4gICAgfSBlbHNlIHtcbiAgICAgIGlmICh0aGlzLm9wdGlvbnMuaWdub3JlV2hpdGVzcGFjZSkge1xuICAgICAgICBsaW5lID0gbGluZS50cmltKCk7XG4gICAgICB9XG4gICAgICByZXRMaW5lcy5wdXNoKGxpbmUpO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiByZXRMaW5lcztcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmTGluZXMob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKSB7IHJldHVybiBsaW5lRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbmV4cG9ydCBmdW5jdGlvbiBkaWZmVHJpbW1lZExpbmVzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykge1xuICBsZXQgb3B0aW9ucyA9IGdlbmVyYXRlT3B0aW9ucyhjYWxsYmFjaywge2lnbm9yZVdoaXRlc3BhY2U6IHRydWV9KTtcbiAgcmV0dXJuIGxpbmVEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIG9wdGlvbnMpO1xufVxuIl19 +}); + +/*istanbul ignore start*/ + +var sentence = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; +exports.sentenceDiff = undefined; +exports. /*istanbul ignore end*/diffSentences = diffSentences; + + + +/*istanbul ignore start*/ +var _base2 = _interopRequireDefault(base); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/var sentenceDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/sentenceDiff = new /*istanbul ignore start*/_base2.default() /*istanbul ignore end*/; +sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; + +function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); +} +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3NlbnRlbmNlLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Z0NBUWdCOztBQVJoQjs7Ozs7Ozt1QkFHTyxJQUFNLHVGQUFlLHFFQUFmO0FBQ2IsYUFBYSxRQUFiLEdBQXdCLFVBQVMsS0FBVCxFQUFnQjtBQUN0QyxTQUFPLE1BQU0sS0FBTixDQUFZLHVCQUFaLENBQVAsQ0FEc0M7Q0FBaEI7O0FBSWpCLFNBQVMsYUFBVCxDQUF1QixNQUF2QixFQUErQixNQUEvQixFQUF1QyxRQUF2QyxFQUFpRDtBQUFFLFNBQU8sYUFBYSxJQUFiLENBQWtCLE1BQWxCLEVBQTBCLE1BQTFCLEVBQWtDLFFBQWxDLENBQVAsQ0FBRjtDQUFqRCIsImZpbGUiOiJzZW50ZW5jZS5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cblxuZXhwb3J0IGNvbnN0IHNlbnRlbmNlRGlmZiA9IG5ldyBEaWZmKCk7XG5zZW50ZW5jZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc3BsaXQoLyhcXFMuKz9bLiE/XSkoPz1cXHMrfCQpLyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZlNlbnRlbmNlcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIHNlbnRlbmNlRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdfQ== +}); + +/*istanbul ignore start*/ + +var css = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; +exports.cssDiff = undefined; +exports. /*istanbul ignore end*/diffCss = diffCss; + + + +/*istanbul ignore start*/ +var _base2 = _interopRequireDefault(base); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/var cssDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/cssDiff = new /*istanbul ignore start*/_base2.default() /*istanbul ignore end*/; +cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); +}; + +function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); +} +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Nzcy5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7O2dDQU9nQjs7QUFQaEI7Ozs7Ozs7dUJBRU8sSUFBTSw2RUFBVSxxRUFBVjtBQUNiLFFBQVEsUUFBUixHQUFtQixVQUFTLEtBQVQsRUFBZ0I7QUFDakMsU0FBTyxNQUFNLEtBQU4sQ0FBWSxlQUFaLENBQVAsQ0FEaUM7Q0FBaEI7O0FBSVosU0FBUyxPQUFULENBQWlCLE1BQWpCLEVBQXlCLE1BQXpCLEVBQWlDLFFBQWpDLEVBQTJDO0FBQUUsU0FBTyxRQUFRLElBQVIsQ0FBYSxNQUFiLEVBQXFCLE1BQXJCLEVBQTZCLFFBQTdCLENBQVAsQ0FBRjtDQUEzQyIsImZpbGUiOiJjc3MuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgRGlmZiBmcm9tICcuL2Jhc2UnO1xuXG5leHBvcnQgY29uc3QgY3NzRGlmZiA9IG5ldyBEaWZmKCk7XG5jc3NEaWZmLnRva2VuaXplID0gZnVuY3Rpb24odmFsdWUpIHtcbiAgcmV0dXJuIHZhbHVlLnNwbGl0KC8oW3t9OjssXXxcXHMrKS8pO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZDc3Mob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKSB7IHJldHVybiBjc3NEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIGNhbGxiYWNrKTsgfVxuIl19 +}); + +/*istanbul ignore start*/ + +var json = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; +exports.jsonDiff = undefined; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; + +exports. /*istanbul ignore end*/diffJson = diffJson; +/*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = canonicalize; + + + +/*istanbul ignore start*/ +var _base2 = _interopRequireDefault(base); + +/*istanbul ignore end*/ + + +/*istanbul ignore start*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/ + +var objectPrototypeToString = Object.prototype.toString; + +var jsonDiff = /*istanbul ignore start*/exports. /*istanbul ignore end*/jsonDiff = new /*istanbul ignore start*/_base2.default() /*istanbul ignore end*/; +// Discriminate between two lines of pretty-printed, serialized JSON where one of them has a +// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: +jsonDiff.useLongestToken = true; + +jsonDiff.tokenize = /*istanbul ignore start*/line.lineDiff. /*istanbul ignore end*/tokenize; +jsonDiff.castInput = function (value) { + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value), undefined, ' '); +}; +jsonDiff.equals = function (left, right) { + return (/*istanbul ignore start*/_base2.default. /*istanbul ignore end*/prototype.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) + ); +}; + +function diffJson(oldObj, newObj, callback) { + return jsonDiff.diff(oldObj, newObj, callback); +} + +// This function handles the presence of circular references by bailing out when encountering an +// object that is already on the "stack" of items being processed. +function canonicalize(obj, stack, replacementStack) { + stack = stack || []; + replacementStack = replacementStack || []; + + var i = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack); + } + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if ( /*istanbul ignore start*/(typeof /*istanbul ignore end*/obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + var sortedKeys = [], + key = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + for (key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(key)) { + sortedKeys.push(key); + } + } + sortedKeys.sort(); + for (i = 0; i < sortedKeys.length; i += 1) { + key = sortedKeys[i]; + canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack); + } + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + return canonicalizedObj; +} +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2pzb24uanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7OztnQ0FtQmdCO3lEQUtBOztBQXhCaEI7Ozs7OztBQUNBOzs7Ozs7O0FBRUEsSUFBTSwwQkFBMEIsT0FBTyxTQUFQLENBQWlCLFFBQWpCOztBQUd6QixJQUFNLCtFQUFXLHFFQUFYOzs7QUFHYixTQUFTLGVBQVQsR0FBMkIsSUFBM0I7O0FBRUEsU0FBUyxRQUFULEdBQW9CLGdFQUFTLFFBQVQ7QUFDcEIsU0FBUyxTQUFULEdBQXFCLFVBQVMsS0FBVCxFQUFnQjtBQUNuQyxTQUFPLE9BQU8sS0FBUCxLQUFpQixRQUFqQixHQUE0QixLQUE1QixHQUFvQyxLQUFLLFNBQUwsQ0FBZSxhQUFhLEtBQWIsQ0FBZixFQUFvQyxTQUFwQyxFQUErQyxJQUEvQyxDQUFwQyxDQUQ0QjtDQUFoQjtBQUdyQixTQUFTLE1BQVQsR0FBa0IsVUFBUyxJQUFULEVBQWUsS0FBZixFQUFzQjtBQUN0QyxTQUFPLGlFQUFLLFNBQUwsQ0FBZSxNQUFmLENBQXNCLEtBQUssT0FBTCxDQUFhLFlBQWIsRUFBMkIsSUFBM0IsQ0FBdEIsRUFBd0QsTUFBTSxPQUFOLENBQWMsWUFBZCxFQUE0QixJQUE1QixDQUF4RCxDQUFQO0lBRHNDO0NBQXRCOztBQUlYLFNBQVMsUUFBVCxDQUFrQixNQUFsQixFQUEwQixNQUExQixFQUFrQyxRQUFsQyxFQUE0QztBQUFFLFNBQU8sU0FBUyxJQUFULENBQWMsTUFBZCxFQUFzQixNQUF0QixFQUE4QixRQUE5QixDQUFQLENBQUY7Q0FBNUM7Ozs7QUFLQSxTQUFTLFlBQVQsQ0FBc0IsR0FBdEIsRUFBMkIsS0FBM0IsRUFBa0MsZ0JBQWxDLEVBQW9EO0FBQ3pELFVBQVEsU0FBUyxFQUFULENBRGlEO0FBRXpELHFCQUFtQixvQkFBb0IsRUFBcEIsQ0FGc0M7O0FBSXpELE1BQUksMkRBQUosQ0FKeUQ7O0FBTXpELE9BQUssSUFBSSxDQUFKLEVBQU8sSUFBSSxNQUFNLE1BQU4sRUFBYyxLQUFLLENBQUwsRUFBUTtBQUNwQyxRQUFJLE1BQU0sQ0FBTixNQUFhLEdBQWIsRUFBa0I7QUFDcEIsYUFBTyxpQkFBaUIsQ0FBakIsQ0FBUCxDQURvQjtLQUF0QjtHQURGOztBQU1BLE1BQUksMEVBQUosQ0FaeUQ7O0FBY3pELE1BQUkscUJBQXFCLHdCQUF3QixJQUF4QixDQUE2QixHQUE3QixDQUFyQixFQUF3RDtBQUMxRCxVQUFNLElBQU4sQ0FBVyxHQUFYLEVBRDBEO0FBRTFELHVCQUFtQixJQUFJLEtBQUosQ0FBVSxJQUFJLE1BQUosQ0FBN0IsQ0FGMEQ7QUFHMUQscUJBQWlCLElBQWpCLENBQXNCLGdCQUF0QixFQUgwRDtBQUkxRCxTQUFLLElBQUksQ0FBSixFQUFPLElBQUksSUFBSSxNQUFKLEVBQVksS0FBSyxDQUFMLEVBQVE7QUFDbEMsdUJBQWlCLENBQWpCLElBQXNCLGFBQWEsSUFBSSxDQUFKLENBQWIsRUFBcUIsS0FBckIsRUFBNEIsZ0JBQTVCLENBQXRCLENBRGtDO0tBQXBDO0FBR0EsVUFBTSxHQUFOLEdBUDBEO0FBUTFELHFCQUFpQixHQUFqQixHQVIwRDtBQVMxRCxXQUFPLGdCQUFQLENBVDBEO0dBQTVEOztBQVlBLE1BQUksT0FBTyxJQUFJLE1BQUosRUFBWTtBQUNyQixVQUFNLElBQUksTUFBSixFQUFOLENBRHFCO0dBQXZCOztBQUlBLE1BQUkseURBQU8saURBQVAsS0FBZSxRQUFmLElBQTJCLFFBQVEsSUFBUixFQUFjO0FBQzNDLFVBQU0sSUFBTixDQUFXLEdBQVgsRUFEMkM7QUFFM0MsdUJBQW1CLEVBQW5CLENBRjJDO0FBRzNDLHFCQUFpQixJQUFqQixDQUFzQixnQkFBdEIsRUFIMkM7QUFJM0MsUUFBSSxhQUFhLEVBQWI7UUFDQSw2REFESixDQUoyQztBQU0zQyxTQUFLLEdBQUwsSUFBWSxHQUFaLEVBQWlCOztBQUVmLFVBQUksSUFBSSxjQUFKLENBQW1CLEdBQW5CLENBQUosRUFBNkI7QUFDM0IsbUJBQVcsSUFBWCxDQUFnQixHQUFoQixFQUQyQjtPQUE3QjtLQUZGO0FBTUEsZUFBVyxJQUFYLEdBWjJDO0FBYTNDLFNBQUssSUFBSSxDQUFKLEVBQU8sSUFBSSxXQUFXLE1BQVgsRUFBbUIsS0FBSyxDQUFMLEVBQVE7QUFDekMsWUFBTSxXQUFXLENBQVgsQ0FBTixDQUR5QztBQUV6Qyx1QkFBaUIsR0FBakIsSUFBd0IsYUFBYSxJQUFJLEdBQUosQ0FBYixFQUF1QixLQUF2QixFQUE4QixnQkFBOUIsQ0FBeEIsQ0FGeUM7S0FBM0M7QUFJQSxVQUFNLEdBQU4sR0FqQjJDO0FBa0IzQyxxQkFBaUIsR0FBakIsR0FsQjJDO0dBQTdDLE1BbUJPO0FBQ0wsdUJBQW1CLEdBQW5CLENBREs7R0FuQlA7QUFzQkEsU0FBTyxnQkFBUCxDQXBEeUQ7Q0FBcEQiLCJmaWxlIjoianNvbi5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5pbXBvcnQge2xpbmVEaWZmfSBmcm9tICcuL2xpbmUnO1xuXG5jb25zdCBvYmplY3RQcm90b3R5cGVUb1N0cmluZyA9IE9iamVjdC5wcm90b3R5cGUudG9TdHJpbmc7XG5cblxuZXhwb3J0IGNvbnN0IGpzb25EaWZmID0gbmV3IERpZmYoKTtcbi8vIERpc2NyaW1pbmF0ZSBiZXR3ZWVuIHR3byBsaW5lcyBvZiBwcmV0dHktcHJpbnRlZCwgc2VyaWFsaXplZCBKU09OIHdoZXJlIG9uZSBvZiB0aGVtIGhhcyBhXG4vLyBkYW5nbGluZyBjb21tYSBhbmQgdGhlIG90aGVyIGRvZXNuJ3QuIFR1cm5zIG91dCBpbmNsdWRpbmcgdGhlIGRhbmdsaW5nIGNvbW1hIHlpZWxkcyB0aGUgbmljZXN0IG91dHB1dDpcbmpzb25EaWZmLnVzZUxvbmdlc3RUb2tlbiA9IHRydWU7XG5cbmpzb25EaWZmLnRva2VuaXplID0gbGluZURpZmYudG9rZW5pemU7XG5qc29uRGlmZi5jYXN0SW5wdXQgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdHlwZW9mIHZhbHVlID09PSAnc3RyaW5nJyA/IHZhbHVlIDogSlNPTi5zdHJpbmdpZnkoY2Fub25pY2FsaXplKHZhbHVlKSwgdW5kZWZpbmVkLCAnICAnKTtcbn07XG5qc29uRGlmZi5lcXVhbHMgPSBmdW5jdGlvbihsZWZ0LCByaWdodCkge1xuICByZXR1cm4gRGlmZi5wcm90b3R5cGUuZXF1YWxzKGxlZnQucmVwbGFjZSgvLChbXFxyXFxuXSkvZywgJyQxJyksIHJpZ2h0LnJlcGxhY2UoLywoW1xcclxcbl0pL2csICckMScpKTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmSnNvbihvbGRPYmosIG5ld09iaiwgY2FsbGJhY2spIHsgcmV0dXJuIGpzb25EaWZmLmRpZmYob2xkT2JqLCBuZXdPYmosIGNhbGxiYWNrKTsgfVxuXG5cbi8vIFRoaXMgZnVuY3Rpb24gaGFuZGxlcyB0aGUgcHJlc2VuY2Ugb2YgY2lyY3VsYXIgcmVmZXJlbmNlcyBieSBiYWlsaW5nIG91dCB3aGVuIGVuY291bnRlcmluZyBhblxuLy8gb2JqZWN0IHRoYXQgaXMgYWxyZWFkeSBvbiB0aGUgXCJzdGFja1wiIG9mIGl0ZW1zIGJlaW5nIHByb2Nlc3NlZC5cbmV4cG9ydCBmdW5jdGlvbiBjYW5vbmljYWxpemUob2JqLCBzdGFjaywgcmVwbGFjZW1lbnRTdGFjaykge1xuICBzdGFjayA9IHN0YWNrIHx8IFtdO1xuICByZXBsYWNlbWVudFN0YWNrID0gcmVwbGFjZW1lbnRTdGFjayB8fCBbXTtcblxuICBsZXQgaTtcblxuICBmb3IgKGkgPSAwOyBpIDwgc3RhY2subGVuZ3RoOyBpICs9IDEpIHtcbiAgICBpZiAoc3RhY2tbaV0gPT09IG9iaikge1xuICAgICAgcmV0dXJuIHJlcGxhY2VtZW50U3RhY2tbaV07XG4gICAgfVxuICB9XG5cbiAgbGV0IGNhbm9uaWNhbGl6ZWRPYmo7XG5cbiAgaWYgKCdbb2JqZWN0IEFycmF5XScgPT09IG9iamVjdFByb3RvdHlwZVRvU3RyaW5nLmNhbGwob2JqKSkge1xuICAgIHN0YWNrLnB1c2gob2JqKTtcbiAgICBjYW5vbmljYWxpemVkT2JqID0gbmV3IEFycmF5KG9iai5sZW5ndGgpO1xuICAgIHJlcGxhY2VtZW50U3RhY2sucHVzaChjYW5vbmljYWxpemVkT2JqKTtcbiAgICBmb3IgKGkgPSAwOyBpIDwgb2JqLmxlbmd0aDsgaSArPSAxKSB7XG4gICAgICBjYW5vbmljYWxpemVkT2JqW2ldID0gY2Fub25pY2FsaXplKG9ialtpXSwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2spO1xuICAgIH1cbiAgICBzdGFjay5wb3AoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnBvcCgpO1xuICAgIHJldHVybiBjYW5vbmljYWxpemVkT2JqO1xuICB9XG5cbiAgaWYgKG9iaiAmJiBvYmoudG9KU09OKSB7XG4gICAgb2JqID0gb2JqLnRvSlNPTigpO1xuICB9XG5cbiAgaWYgKHR5cGVvZiBvYmogPT09ICdvYmplY3QnICYmIG9iaiAhPT0gbnVsbCkge1xuICAgIHN0YWNrLnB1c2gob2JqKTtcbiAgICBjYW5vbmljYWxpemVkT2JqID0ge307XG4gICAgcmVwbGFjZW1lbnRTdGFjay5wdXNoKGNhbm9uaWNhbGl6ZWRPYmopO1xuICAgIGxldCBzb3J0ZWRLZXlzID0gW10sXG4gICAgICAgIGtleTtcbiAgICBmb3IgKGtleSBpbiBvYmopIHtcbiAgICAgIC8qIGlzdGFuYnVsIGlnbm9yZSBlbHNlICovXG4gICAgICBpZiAob2JqLmhhc093blByb3BlcnR5KGtleSkpIHtcbiAgICAgICAgc29ydGVkS2V5cy5wdXNoKGtleSk7XG4gICAgICB9XG4gICAgfVxuICAgIHNvcnRlZEtleXMuc29ydCgpO1xuICAgIGZvciAoaSA9IDA7IGkgPCBzb3J0ZWRLZXlzLmxlbmd0aDsgaSArPSAxKSB7XG4gICAgICBrZXkgPSBzb3J0ZWRLZXlzW2ldO1xuICAgICAgY2Fub25pY2FsaXplZE9ialtrZXldID0gY2Fub25pY2FsaXplKG9ialtrZXldLCBzdGFjaywgcmVwbGFjZW1lbnRTdGFjayk7XG4gICAgfVxuICAgIHN0YWNrLnBvcCgpO1xuICAgIHJlcGxhY2VtZW50U3RhY2sucG9wKCk7XG4gIH0gZWxzZSB7XG4gICAgY2Fub25pY2FsaXplZE9iaiA9IG9iajtcbiAgfVxuICByZXR1cm4gY2Fub25pY2FsaXplZE9iajtcbn1cbiJdfQ== +}); + +/*istanbul ignore start*/ + + +var parsePatch_1 = parsePatch; +function parsePatch(uniDiff) { + /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + var diffstr = uniDiff.split('\n'), + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); + + // Parse diff metadata + while (i < diffstr.length) { + var line = diffstr[i]; + + // File header found, end parsing diff metadata + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } + + // Diff index + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + if (header) { + index.index = header[1]; + } + + i++; + } + + // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + parseFileHeader(index); + parseFileHeader(index); + + // Parse hunks + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } + + // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + function parseFileHeader(index) { + var fileHeader = /^(\-\-\-|\+\+\+)\s+(\S*)\s?(.*?)\s*$/.exec(diffstr[i]); + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + index[keyPrefix + 'FileName'] = fileHeader[2]; + index[keyPrefix + 'Header'] = fileHeader[3]; + + i++; + } + } + + // Parses a hunk + // This assumes that we are at the start of a hunk. + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [] + }; + + var addCount = 0, + removeCount = 0; + for (; i < diffstr.length; i++) { + var operation = diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } + + // Handle the empty block count case + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } + + // Perform optional sanity checking + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; +} + + +var parse = /*#__PURE__*/Object.defineProperty({ + parsePatch: parsePatch_1 +}, '__esModule', {value: true}); + +/*istanbul ignore start*/ + + + +var _default = /*istanbul ignore end*/function (start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } + + // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } + + // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + if (minLine <= start - localOffset) { + return - localOffset++; + } + + backwardExhausted = true; + return iterator(); + } + + // We tried to fit hunk before text beginning and beyond text lenght, then + // hunk can't fit on the text. Return undefined + }; +}; + + +var distanceIterator = /*#__PURE__*/Object.defineProperty({ + default: _default +}, '__esModule', {value: true}); + +/*istanbul ignore start*/ + + +var applyPatch_1 = applyPatch; +/*istanbul ignore start*/var applyPatches_1 = applyPatches; + + + + + +/*istanbul ignore start*/ +var _distanceIterator2 = _interopRequireDefault(distanceIterator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/*istanbul ignore end*/function applyPatch(source, uniDiff) { + /*istanbul ignore start*/var /*istanbul ignore end*/options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + if (typeof uniDiff === 'string') { + uniDiff = /*istanbul ignore start*/(0, parse.parsePatch) /*istanbul ignore end*/(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } + + // Apply the diff to the input + var lines = source.split('\n'), + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) /*istanbul ignore start*/{ + return (/*istanbul ignore end*/line === patchContent + ); + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/, + addEOFNL = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + + /** + * Checks if the hunk exactly fits on the provided location + */ + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line[0], + content = line.substr(1); + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + toPos++; + } + } + + return true; + } + + // Search best fit offsets for each hunk based on the previous ones + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + + var iterator = /*istanbul ignore start*/(0, _distanceIterator2.default) /*istanbul ignore end*/(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } + + // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } + + // Apply patch hunks + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.offset + _hunk.newStart - 1; + if (_hunk.newLines == 0) { + _toPos++; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line[0], + content = line.substr(1); + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } + + // Handle EOFNL insertion/removal + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + } + } else if (addEOFNL) { + lines.push(''); + } + return lines.join('\n'); +} + +// Wrapper that supports multiple file patches via callbacks. +function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = /*istanbul ignore start*/(0, parse.parsePatch) /*istanbul ignore end*/(uniDiff); + } + + var currentIndex = 0; + function processIndex() { + var index = uniDiff[currentIndex++]; + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent); + + setTimeout(processIndex, 0); + }); + } + processIndex(); +} + + +var apply = /*#__PURE__*/Object.defineProperty({ + applyPatch: applyPatch_1, + applyPatches: applyPatches_1 +}, '__esModule', {value: true}); + +/*istanbul ignore start*/ + + +var structuredPatch_1 = structuredPatch; +/*istanbul ignore start*/var createTwoFilesPatch_1 = createTwoFilesPatch; +/*istanbul ignore start*/var createPatch_1 = createPatch; + + + +/*istanbul ignore start*/ +function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } + +/*istanbul ignore end*/function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = { context: 4 }; + } + + var diff = /*istanbul ignore start*/(0, line.diffLines) /*istanbul ignore end*/(oldStr, newStr); + diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + /*istanbul ignore start*/ + var _loop = function _loop( /*istanbul ignore end*/i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + /*istanbul ignore start*/ + var _curRange; + + /*istanbul ignore end*/ + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + + // Output our changes + /*istanbul ignore start*/(_curRange = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); + + // Track the updated file position + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + /*istanbul ignore start*/ + var _curRange2; + + /*istanbul ignore end*/ + // Overlapping + /*istanbul ignore start*/(_curRange2 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange2 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines))); + } else { + /*istanbul ignore start*/ + var _curRange3; + + /*istanbul ignore end*/ + // end the range and output + var contextSize = Math.min(lines.length, options.context); + /*istanbul ignore start*/(_curRange3 = /*istanbul ignore end*/curRange).push. /*istanbul ignore start*/apply /*istanbul ignore end*/( /*istanbul ignore start*/_curRange3 /*istanbul ignore end*/, /*istanbul ignore start*/_toConsumableArray( /*istanbul ignore end*/contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + if (lines.length == 0 && !oldEOFNewline) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } else if (!oldEOFNewline || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + hunks.push(hunk); + + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + /*istanbul ignore start*/ + _loop( /*istanbul ignore end*/i); + } + + return { + oldFileName: oldFileName, newFileName: newFileName, + oldHeader: oldHeader, newHeader: newHeader, + hunks: hunks + }; +} + +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + + var ret = []; + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; +} + +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} + + +var create = /*#__PURE__*/Object.defineProperty({ + structuredPatch: structuredPatch_1, + createTwoFilesPatch: createTwoFilesPatch_1, + createPatch: createPatch_1 +}, '__esModule', {value: true}); + +/*istanbul ignore start*/ + + +var convertChangesToDMP_1 = convertChangesToDMP; +// See: http://code.google.com/p/google-diff-match-patch/wiki/API +function convertChangesToDMP(changes) { + var ret = [], + change = /*istanbul ignore start*/void 0 /*istanbul ignore end*/, + operation = /*istanbul ignore start*/void 0 /*istanbul ignore end*/; + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + return ret; +} + + +var dmp = /*#__PURE__*/Object.defineProperty({ + convertChangesToDMP: convertChangesToDMP_1 +}, '__esModule', {value: true}); + +/*istanbul ignore start*/ + + +var convertChangesToXML_1 = convertChangesToXML; +function convertChangesToXML(changes) { + var ret = []; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + if (change.added) { + ret.push('<ins>'); + } else if (change.removed) { + ret.push('<del>'); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push('</ins>'); + } else if (change.removed) { + ret.push('</del>'); + } + } + return ret.join(''); +} + +function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(/</g, '<'); + n = n.replace(/>/g, '>'); + n = n.replace(/"/g, '"'); + + return n; +} + + +var xml = /*#__PURE__*/Object.defineProperty({ + convertChangesToXML: convertChangesToXML_1 +}, '__esModule', {value: true}); + +/*istanbul ignore start*/ + +var lib = createCommonjsModule(function (module, exports) { + +exports.__esModule = true; +exports.canonicalize = exports.convertChangesToXML = exports.convertChangesToDMP = exports.parsePatch = exports.applyPatches = exports.applyPatch = exports.createPatch = exports.createTwoFilesPatch = exports.structuredPatch = exports.diffJson = exports.diffCss = exports.diffSentences = exports.diffTrimmedLines = exports.diffLines = exports.diffWordsWithSpace = exports.diffWords = exports.diffChars = exports.Diff = undefined; +/*istanbul ignore end*/ + + +/*istanbul ignore start*/ +var _base2 = _interopRequireDefault(base); + +/*istanbul ignore end*/ + + + + + + + + + + + + + + + + + + + + + + +/*istanbul ignore start*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* See LICENSE file for terms of use */ + +/* + * Text diff implementation. + * + * This library supports the following APIS: + * JsDiff.diffChars: Character by character diff + * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * JsDiff.diffLines: Line based diff + * + * JsDiff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ +exports. /*istanbul ignore end*/Diff = _base2.default; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffChars = character.diffChars; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffWords = word.diffWords; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffWordsWithSpace = word.diffWordsWithSpace; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffLines = line.diffLines; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffTrimmedLines = line.diffTrimmedLines; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffSentences = sentence.diffSentences; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffCss = css.diffCss; +/*istanbul ignore start*/exports. /*istanbul ignore end*/diffJson = json.diffJson; +/*istanbul ignore start*/exports. /*istanbul ignore end*/structuredPatch = create.structuredPatch; +/*istanbul ignore start*/exports. /*istanbul ignore end*/createTwoFilesPatch = create.createTwoFilesPatch; +/*istanbul ignore start*/exports. /*istanbul ignore end*/createPatch = create.createPatch; +/*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatch = apply.applyPatch; +/*istanbul ignore start*/exports. /*istanbul ignore end*/applyPatches = apply.applyPatches; +/*istanbul ignore start*/exports. /*istanbul ignore end*/parsePatch = parse.parsePatch; +/*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToDMP = dmp.convertChangesToDMP; +/*istanbul ignore start*/exports. /*istanbul ignore end*/convertChangesToXML = xml.convertChangesToXML; +/*istanbul ignore start*/exports. /*istanbul ignore end*/canonicalize = json.canonicalize; +//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQWdCQTs7Ozs7O0FBQ0E7O0FBQ0E7O0FBQ0E7O0FBQ0E7O0FBRUE7O0FBQ0E7O0FBRUE7O0FBQ0E7O0FBQ0E7O0FBRUE7O0FBQ0E7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztnQ0FHRTt5REFFQTt5REFDQTt5REFDQTt5REFDQTt5REFDQTt5REFDQTt5REFFQTt5REFDQTt5REFFQTt5REFDQTt5REFDQTt5REFDQTt5REFDQTt5REFDQTt5REFDQTt5REFDQTt5REFDQSIsImZpbGUiOiJpbmRleC5qcyIsInNvdXJjZXNDb250ZW50IjpbIi8qIFNlZSBMSUNFTlNFIGZpbGUgZm9yIHRlcm1zIG9mIHVzZSAqL1xuXG4vKlxuICogVGV4dCBkaWZmIGltcGxlbWVudGF0aW9uLlxuICpcbiAqIFRoaXMgbGlicmFyeSBzdXBwb3J0cyB0aGUgZm9sbG93aW5nIEFQSVM6XG4gKiBKc0RpZmYuZGlmZkNoYXJzOiBDaGFyYWN0ZXIgYnkgY2hhcmFjdGVyIGRpZmZcbiAqIEpzRGlmZi5kaWZmV29yZHM6IFdvcmQgKGFzIGRlZmluZWQgYnkgXFxiIHJlZ2V4KSBkaWZmIHdoaWNoIGlnbm9yZXMgd2hpdGVzcGFjZVxuICogSnNEaWZmLmRpZmZMaW5lczogTGluZSBiYXNlZCBkaWZmXG4gKlxuICogSnNEaWZmLmRpZmZDc3M6IERpZmYgdGFyZ2V0ZWQgYXQgQ1NTIGNvbnRlbnRcbiAqXG4gKiBUaGVzZSBtZXRob2RzIGFyZSBiYXNlZCBvbiB0aGUgaW1wbGVtZW50YXRpb24gcHJvcG9zZWQgaW5cbiAqIFwiQW4gTyhORCkgRGlmZmVyZW5jZSBBbGdvcml0aG0gYW5kIGl0cyBWYXJpYXRpb25zXCIgKE15ZXJzLCAxOTg2KS5cbiAqIGh0dHA6Ly9jaXRlc2VlcnguaXN0LnBzdS5lZHUvdmlld2RvYy9zdW1tYXJ5P2RvaT0xMC4xLjEuNC42OTI3XG4gKi9cbmltcG9ydCBEaWZmIGZyb20gJy4vZGlmZi9iYXNlJztcbmltcG9ydCB7ZGlmZkNoYXJzfSBmcm9tICcuL2RpZmYvY2hhcmFjdGVyJztcbmltcG9ydCB7ZGlmZldvcmRzLCBkaWZmV29yZHNXaXRoU3BhY2V9IGZyb20gJy4vZGlmZi93b3JkJztcbmltcG9ydCB7ZGlmZkxpbmVzLCBkaWZmVHJpbW1lZExpbmVzfSBmcm9tICcuL2RpZmYvbGluZSc7XG5pbXBvcnQge2RpZmZTZW50ZW5jZXN9IGZyb20gJy4vZGlmZi9zZW50ZW5jZSc7XG5cbmltcG9ydCB7ZGlmZkNzc30gZnJvbSAnLi9kaWZmL2Nzcyc7XG5pbXBvcnQge2RpZmZKc29uLCBjYW5vbmljYWxpemV9IGZyb20gJy4vZGlmZi9qc29uJztcblxuaW1wb3J0IHthcHBseVBhdGNoLCBhcHBseVBhdGNoZXN9IGZyb20gJy4vcGF0Y2gvYXBwbHknO1xuaW1wb3J0IHtwYXJzZVBhdGNofSBmcm9tICcuL3BhdGNoL3BhcnNlJztcbmltcG9ydCB7c3RydWN0dXJlZFBhdGNoLCBjcmVhdGVUd29GaWxlc1BhdGNoLCBjcmVhdGVQYXRjaH0gZnJvbSAnLi9wYXRjaC9jcmVhdGUnO1xuXG5pbXBvcnQge2NvbnZlcnRDaGFuZ2VzVG9ETVB9IGZyb20gJy4vY29udmVydC9kbXAnO1xuaW1wb3J0IHtjb252ZXJ0Q2hhbmdlc1RvWE1MfSBmcm9tICcuL2NvbnZlcnQveG1sJztcblxuZXhwb3J0IHtcbiAgRGlmZixcblxuICBkaWZmQ2hhcnMsXG4gIGRpZmZXb3JkcyxcbiAgZGlmZldvcmRzV2l0aFNwYWNlLFxuICBkaWZmTGluZXMsXG4gIGRpZmZUcmltbWVkTGluZXMsXG4gIGRpZmZTZW50ZW5jZXMsXG5cbiAgZGlmZkNzcyxcbiAgZGlmZkpzb24sXG5cbiAgc3RydWN0dXJlZFBhdGNoLFxuICBjcmVhdGVUd29GaWxlc1BhdGNoLFxuICBjcmVhdGVQYXRjaCxcbiAgYXBwbHlQYXRjaCxcbiAgYXBwbHlQYXRjaGVzLFxuICBwYXJzZVBhdGNoLFxuICBjb252ZXJ0Q2hhbmdlc1RvRE1QLFxuICBjb252ZXJ0Q2hhbmdlc1RvWE1MLFxuICBjYW5vbmljYWxpemVcbn07XG4iXX0= +}); + +// objects and functions for formatting diffs with partial context. see the 'makeHunks()' documentation, below + +function calcLen (linechanges, ab) { + let len = 0; + for (let ci = 0; ci < linechanges.length; ci++) { + switch (linechanges[ci].type) { + case REMOVED: + len += ab[0]; + break + case ADDED: + len += ab[1]; + break + case UNMODIFIED: + len++; + break + default: + throw Error('unknown change type: ' + linechanges[ci].type) + } + } + return len +} + +function Hunk (aoff, boff, changes) { + this.changes = changes; + this.aoff = aoff; + this.boff = boff; + this._alen = -1; + this._blen = -1; +} + +Object.defineProperty (Hunk.prototype, 'alen', { + get: function () { return this._alen === -1 ? (this._alen = calcLen(this.changes, [1,0])) : this._alen } +}); + +Object.defineProperty (Hunk.prototype, 'blen', { + get: function () { return this._blen === -1 ? (this._blen = calcLen(this.changes, [0,1])) : this._blen } +}); + +Hunk.prototype.unified = function () { + let ret = [this.unifiedHeader()]; + this.changes.forEach(function(c) { + ret.push(c.unified()); + }); + // console.log("expect:\n'" + ret.join("'\n'") + "'") // useful for creating test output + return ret.join('\n') +}; + +Hunk.prototype.unifiedHeader = function () { + let alen = this.alen === 1 ? '' : ',' + this.alen; + let blen = this.blen === 1 ? '' : ',' + this.blen; + // empty hunks show zeroith line (prior). hunks with lines show first line number + let afudg = this.alen === 0 ? 0 : 1; + let bfudg = this.blen === 0 ? 0 : 1; + return '@@ -' + (this.aoff+afudg) + alen + ' +' + (this.boff+bfudg) + blen + ' @@' +}; + +Hunk.prototype.shorthand = function () { + return this.changes.reduce(function(s,c){ return s + c.type }, '') +}; + +Hunk.prototype.toString = function () { + return "{" + this.shorthand() + "} " + this.unifiedHeader() +}; + +const ADDED = '+'; +const REMOVED = '-'; +const UNMODIFIED = 's'; + +function type2unified (type) { return type === 's' ? ' ' : type } + +// LineChange objects represent a single line of change. Converting diff.diffLine() result array into LineChange +// object array: +// +// 1. simplifies logic that needs work with lines +// 2. separates this extension module from specific dependency on the diff library +function LineChange (type, text) { + this.type = type; // ADDED, REMOVED, UNMODIFIED + this.text = text; +} +LineChange.prototype.unified = function () { + return type2unified(this.type) + this.text +}; +LineChange.prototype.toString = function () { return this.unified() }; + +// convert a single change from diff.diffLines() into a single line string +// (handy for debugging) +function change2string (c, maxwidth) { + maxwidth = maxwidth || 60; + let ret = c.count + ': ' + type2unified(c.type); + let lim = Math.min(maxwidth - ret.length, c.value.length-1); // remove last newline + let txt = c.value.substring(0,lim).replace(/\n/g, ',') + (c.value.length > (lim+1) ? '...' : ''); + return ret + txt +} + +// Convert a change as returned from diff.diffLines() into an LineChange objects with offset information. +// +// change - object returned from diff.diffLines() containing one or more lines of change info +// select - (int) +// positive, return up to this many lines from the start of change. +// negative, return up to this many lines from the end of the change. +// zero, return empty array +// undefined, return all lines +// +function lineChanges (change, select) { + // debug: + // console.log(change2str(change) + (select === undefined ? '' : ' (select:' + select + ')')) + if (select === 0) { + return [] + } + let lines = []; + let v = change.value; + if (select === undefined) { + lines = v.split('\n'); + if (!lines[lines.length-1]) { lines.pop(); } // remove terminating new line + } else if(select > 0) { + let i = nthIndexOf(v, '\n', 0, select, false); + lines = v.substring(0,i).split('\n'); + } else { + let len = v[v.length-1] === '\n' ? v.length-1 : v.length; + let i = nthIndexOf(v, '\n', len-1, -select, true); + lines = v.substring(i+1, len).split('\n'); + } + return lines.map(function (line){ return new LineChange(change.type, line)}) +} + +// convert a list of changes into a shorthand notation like 'ss--+++ss-+ss' +function changes2shorthand (changes) { + return '{' + changes.reduce(function (s,c) { for(let i=0; i< c.count; i++) s += c.type; return s }, '') + '}' +} + +// concat-in-place, a -> b and return b +function concatTo (a, b) { + Array.prototype.push.apply(b, a); + return b +} + +// Make Hunk objects from changes as returned from a call to unidiff.lineChanges(). Hunks are collections +// of continuous line changes, therefore every hunk after the first marks a gap +// where unmodified context lines are skipped. +// +// let 's' represent an unmodifed line 'same' +// '-' represent a removed line +// '+' represent an added line +// +// then hunks with a context of 2 could might like this: +// +// hunk hunk hunk +// ___|____ ___|__ ___|___ +// | | | | | | +// sssss----++ssssssssssssss-ss--sssssssss+++++ssssssssss +// +// or this: +// +// hunk hunk hunk +// ___|____ ______|_______ ____|___ +// | | | | | | +// ++++++++sssssssss+++ssss---++sssssss--++++++ +// +// notice that with a context of 2, series of 4 or fewer unmodified lines are included in the same hunk. +// +// basic algo with context of 3, for illustration: +// +// 0. loop (over each block change) +// modified block: +// add all modified lines, continue loop 0 +// +// unmodified block: +// first hunk: collect tail portion, continue +// subsequent hunks: get head portion, and tail (iff there are more changes) +// head + tail <= 6 ? +// add all to current hunk, continue loop 0 +// head + tail > 6 ? +// finish hunk with head portion +// start new hunk with tail portion (iff there are more changes), continue loop 0 +// +function makeHunks (changes, precontext, postcontext) { + + //console.log('--------\nmakeHunks(' + [changes2shorthand(changes), precontext, postcontext].join(', ') + ')') + let ret = []; // completed hunks to return + let lchanges = []; // accumulated line changes (continous/no-gap) to put into next hunk + let lskipped = 0; // skipped context to take into account in next hunk line numbers + function finishHunk () { + if (lchanges.length) { + let aoff = lskipped, boff = lskipped; + if (ret.length) { + let prev = ret[ret.length-1]; + aoff += prev.aoff + prev.alen; + boff += prev.boff + prev.blen; + } + // add hunk and reset state + ret.push(new Hunk(aoff, boff, lchanges)); + lchanges = []; + lskipped = 0; + } + // else keep state (lskipped) and continue + } + + for (let ci=0; ci < changes.length; ci++) { + let change = changes[ci]; + if (change.type === UNMODIFIED) { + // add context + let ctx_after = ci > 0 ? postcontext : 0; // context lines following previous change + let ctx_before = ci < changes.length ? precontext : 0; // context lines preceding next change (iff there are more changes) + let skip = Math.max(change.count - (ctx_after + ctx_before), 0); + if (skip > 0) { + concatTo(lineChanges(change, ctx_after), lchanges); // finish up previous hunk + finishHunk(); + concatTo(lineChanges(change, -ctx_before), lchanges); + lskipped = skip; // remember skipped for next hunk + } else { + concatTo(lineChanges(change), lchanges); // add all context + } + } else { + concatTo(lineChanges(change), lchanges); // add all modifications + } + } + finishHunk(); + //console.log(ret.map(function(h){ return h.toString() }).join('\n')) + return ret +} + +// no safty checks. caller knows that there are at least n occurances of v in s to be found. +// reverse will search from high to low using lastIndexOf(). +function nthIndexOf (s, v, from, n, reverse) { + let d = reverse ? -1 : 1; + from -= d; + for (let c=0; c<n; c++) { + from = reverse ? s.lastIndexOf(v, from + d) : s.indexOf(v, from + d); + } + return from +} + +// for testing and debugging +var hunk_1 = function (aoff, boff, lchanges) { return new Hunk(aoff, boff, lchanges) }; +var linechange = function (type, text) { return new LineChange(type, text)}; +var lineChanges_1 = lineChanges; +var change2string_1 = change2string; +var changes2shorthand_1 = changes2shorthand; +var nthIndexOf_1 = nthIndexOf; + +// main API +var makeHunks_1 = makeHunks; +var ADDED_1 = ADDED; +var REMOVED_1 = REMOVED; +var UNMODIFIED_1 = UNMODIFIED; + +var hunk = { + hunk: hunk_1, + linechange: linechange, + lineChanges: lineChanges_1, + change2string: change2string_1, + changes2shorthand: changes2shorthand_1, + nthIndexOf: nthIndexOf_1, + makeHunks: makeHunks_1, + ADDED: ADDED_1, + REMOVED: REMOVED_1, + UNMODIFIED: UNMODIFIED_1 +}; + +var unidiff = createCommonjsModule(function (module, exports) { + + + + + +// return a change type code for the change (returned from diff.diffLines()) +function changeType (change) { + if (change.added) { + return hunk.ADDED + } else if (change.removed) { + return hunk.REMOVED + } else { + return hunk.UNMODIFIED + } +} + +// Given changes from a call to diff.diffLines(), assign each change a type code and +// check that no two of same type occur in a row +function checkAndAssignTypes (changes) { + if (changes.length === 0) { return [] } + + changes[0].type = changeType(changes[0]); + return changes.reduce(function (a, b, i) { + b.type = changeType(b); + if (a.type === b.type) { + throw Error('repeating change types are not handled: ' + a.type + ' (at ' + (i-1) + ' and ' + i + ')') + } + return b + }) +} + + +// convert an array of results from diff.diffLines() into text in unified diff format. +// return empty string if there are no changes. +function formatLines (changes, opt) { + checkAndAssignTypes(changes); + opt = opt || {}; + opt.aname = opt.aname || 'a'; + opt.bname = opt.bname || 'b'; + let context = (opt.context || opt.context === 0) ? opt.context : 0; + opt.pre_context = (opt.pre_context || opt.pre_context === 0) ? opt.pre_context : context; + opt.post_context = (opt.post_context || opt.post_context === 0) ? opt.post_context : context; + + let hunks = hunk.makeHunks(changes, opt.pre_context, opt.post_context); + if (hunks.length) { + let ret = []; + ret.push('--- ' + opt.aname); + ret.push('+++ ' + opt.bname); + hunks.forEach(function (h) { + ret.push(h.unified()); + }); + return ret.join('\n') + } else { + return '' + } +} + +// same as jsdiff.diffLines, but returns empty array when there are no changes (instead of an array with a single +// unmodified change object) +function diffLines (a, b, cb) { + a = Array.isArray(a) ? a.join('\n') + '\n' : a; + b = Array.isArray(b) ? b.join('\n') + '\n' : b; + let ret = lib.diffLines(a, b, cb); + if (ret.length === 1 && !ret[0].added && !ret[0].removed) { + return [] + } else { + return ret + } +} + +function diffAsText (a, b, opt) { + return formatLines(diffLines(a, b), opt) +} + +// handy assertion function that asserts that two arrays or two multi-line strings are the same and reports +// differences to console.log in unified format if there are differences. +// +// actual - array or multi-line string to compare +// expected - array or multi-line string to compare +// label - label to clarify output if there are differences +// okFn - function like tape.ok that takes two arguments: +// expression - true if OK, false if failed test +// msg - a one-line message that prints upon failure +// logFn - function to call with diff output when there are differences (defaults to console.log) +// +function assertEqual (actual, expected, okFn, label, logFn) { + logFn = logFn || console.log; + okFn = okFn.ok || okFn; + let diff = diffAsText(actual, expected, {context: 3, aname: label + " (actual)", bname: label + ' (expected)'}); + okFn(!diff, label); + if (diff) { + diff.split('\n').forEach(function (line) { + logFn(' ' + line); + }); + } +} + +exports.assertEqual = assertEqual; +exports.diffAsText = diffAsText; +exports.formatLines = formatLines; +exports.diffLines = diffLines; + +Object.keys(lib).forEach(function (k) { + if (!exports[k]) { + exports[k] = lib[k]; + } +}); +}); + +const fs = require('fs'); +const path = require('path'); +const runfiles = require(process.env['BAZEL_NODE_RUNFILES_HELPER']); + +function findGoldenInGenerated(golden, actual) { + const goldenLines = golden.split(/[\r\n]+/g).map(l => l.trim()); + const actualLines = actual.split(/[\r\n]+/g).map(l => l.trim()); + // Note: this is not the fastest subsequence algorithm. + nextActualLine: for (let i = 0; i < actualLines.length; i++) { + for (let j = 0; j < goldenLines.length; j++) { + if (actualLines[i + j] !== goldenLines[j]) { + continue nextActualLine; + } + } + // A match! + return true; + } + // No match. + return false; +} + +function main(args) { + const [mode, golden_no_debug, golden_debug, actual] = args; + const actualPath = runfiles.resolveWorkspaceRelative(actual); + const debugBuild = /\/bazel-out\/[^/\s]*-dbg\//.test(actualPath); + const golden = debugBuild ? golden_debug : golden_no_debug; + const actualContents = fs.readFileSync(actualPath, 'utf-8').replace(/\r\n/g, '\n'); + const goldenContents = + fs.readFileSync(runfiles.resolveWorkspaceRelative(golden), 'utf-8').replace(/\r\n/g, '\n'); + + if (actualContents === goldenContents) { + return 0; + } + if (mode === '--out') { + // Write to golden file + fs.writeFileSync(runfiles.resolveWorkspaceRelative(golden), actualContents); + console.error(`Replaced ${path.join(process.cwd(), golden)}`); + return 0; + } + if (mode === '--verify') { + // Compare the generated file to the golden file. + const diff = unidiff.diffLines(goldenContents, actualContents); + let prettyDiff = + unidiff.formatLines(diff, {aname: `[workspace]/${golden}`, bname: `[bazel-out]/${actual}`}); + if (prettyDiff.length > 5000) { + prettyDiff = prettyDiff.substr(0, 5000) + '/n...elided...'; + } + console.error(`Generated output doesn't match: + +${prettyDiff} + +If the bazel-out content is correct, you can update the workspace file by running: + + bazel run ${debugBuild ? '--compilation_mode=dbg ' : ''}${ + process.env['TEST_TARGET'].replace(/_bin$/, '')}.update +`); + return 1; + } + if (mode === '--substring') { + // Verify that the golden file is contained _somewhere_ in the generated + // file. + const diff = findGoldenInGenerated(goldenContents, actualContents); + if (diff) { + console.error(`Unable to find golden contents inside of the the generated file: + +${goldenContents} +`); + return 1; + } + return 0; + } + throw new Error('unknown mode', mode); +} + +if (require.main === module) { + process.exitCode = main(process.argv.slice(2)); +}
diff --git a/internal/pkg_npm/test/BUILD.bazel b/internal/pkg_npm/test/BUILD.bazel index 72bd5be..d42f795 100644 --- a/internal/pkg_npm/test/BUILD.bazel +++ b/internal/pkg_npm/test/BUILD.bazel
@@ -1,5 +1,4 @@ load("@build_bazel_rules_nodejs//:index.bzl", "pkg_npm") -load("//packages/rollup:index.bzl", "rollup_bundle") load("//packages/typescript:index.bzl", "ts_project") load("@bazel_skylib//rules:write_file.bzl", "write_file") @@ -16,15 +15,6 @@ tsconfig = {}, ) -rollup_bundle( - name = "rollup/bundle/subdirectory", - entry_points = { - "foo.ts": "index", - }, - output_dir = True, - deps = [":ts_project"], -) - pkg_npm( name = "dependent_pkg", srcs = ["dependent_file"], @@ -44,9 +34,7 @@ "replace_me": "replaced", }, deps = [ - ":bundle.min.js", ":produces_files", - ":rollup/bundle/subdirectory", ":ts_project", "//internal/pkg_npm/test/transition:test_lib", ], @@ -54,18 +42,10 @@ pkg_npm( name = "test_noop_pkg", - # Special case where these is a single dep that is a directory artifact - # then we assume the package is contained within that single directory - # and the pkg_npm rules does not need to copy any files - deps = [":rollup/bundle/subdirectory"], ) pkg_npm( name = "test_noop2_pkg", - # Special case where these is a single dep that is a directory artifact - # then we assume the package is contained within that single directory - # and the pkg_npm rules does not need to copy any files - srcs = [":rollup/bundle/subdirectory"], ) sh_test(
diff --git a/internal/pkg_web/test/BUILD.bazel b/internal/pkg_web/test/BUILD.bazel index e6fcaa6..0c8171f 100644 --- a/internal/pkg_web/test/BUILD.bazel +++ b/internal/pkg_web/test/BUILD.bazel
@@ -1,6 +1,3 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "pkg_web") -load("@npm//@babel/cli:index.bzl", "babel") -load("//packages/rollup:index.bzl", "rollup_bundle") load("//packages/typescript:index.bzl", "ts_project") package(default_visibility = ["//visibility:public"]) @@ -9,45 +6,4 @@ name = "script", srcs = ["script.ts"], tsconfig = {}, -) - -rollup_bundle( - name = "bundle", - entry_point = ":script.ts", - sourcemap = "true", - deps = [":script"], -) - -babel( - name = "bundle.es2015", - outs = [ - "bundle.es2015.js", - "bundle.es2015.js.map", - ], - args = [ - "$(execpath :bundle.js)", - "--no-babelrc", - "--source-maps", - "--presets=@babel/preset-env", - "--out-file", - "$(execpath :bundle.es2015.js)", - ], - data = [ - "bundle.js", - "bundle.js.map", - "@npm//@babel/preset-env", - ], -) - -pkg_web( - name = "pkg", - srcs = [ - "index.html", - ":bundle", - ":bundle.es2015", - ], - stamp = "@rules_nodejs//nodejs/stamp:always", - substitutions = { - "${version}": "{BUILD_SCM_VERSION}", - }, ) \ No newline at end of file
diff --git a/internal/pkg_web/test2/BUILD.bazel b/internal/pkg_web/test2/BUILD.bazel index 3e08586..d07fcb7 100644 --- a/internal/pkg_web/test2/BUILD.bazel +++ b/internal/pkg_web/test2/BUILD.bazel
@@ -1,33 +1,4 @@ load("@build_bazel_rules_nodejs//:index.bzl", "pkg_web") -load("@npm//@babel/cli:index.bzl", "babel") -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "local_bundle", - entry_point = ":script.js", - sourcemap = "true", -) - -babel( - name = "local_bundle.es2015", - outs = [ - "local_bundle.es2015.js", - "local_bundle.es2015.js.map", - ], - args = [ - "$(execpath :local_bundle.js)", - "--no-babelrc", - "--source-maps", - "--presets=@babel/preset-env", - "--out-file", - "$(execpath :local_bundle.es2015.js)", - ], - data = [ - "local_bundle.js", - "local_bundle.js.map", - "@npm//@babel/preset-env", - ], -) # Same exts as //internal/pkg_web/test-exports, //internal/pkg_web/test2/rel-exports @@ -40,12 +11,6 @@ name = "pkg", srcs = [ "index.html", - # bundles from a different directory - "//internal/pkg_web/test:bundle.es2015", - "//internal/pkg_web/test:bundle", - # bundles in the current path - ":local_bundle.es2015", - ":local_bundle", ] + # bin + gen + exported files from a different directory ["//internal/pkg_web/test-exports:bin-" + e for e in EXTS] +
diff --git a/internal/runfiles/BUILD.bazel b/internal/runfiles/BUILD.bazel index 8c0e1a7..33874b5 100644 --- a/internal/runfiles/BUILD.bazel +++ b/internal/runfiles/BUILD.bazel
@@ -1,21 +1,5 @@ # BEGIN-INTERNAL -load("//:index.bzl", "generated_file_test", "js_library") -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "runfiles_pkg_bundled", - config_file = "rollup.config.js", - entry_points = { - "//packages/runfiles:index.js": "index_bundled", - }, - format = "cjs", - sourcemap = "false", - deps = [ - "//packages/runfiles:runfiles_lib", - "@npm//@rollup/plugin-commonjs", - "@npm//@rollup/plugin-node-resolve", - ], -) +load("//:index.bzl", "js_library") js_library( name = "runfiles_js", @@ -23,14 +7,6 @@ visibility = ["//internal/linker:__pkg__"], ) -# Assert that we keep the `index.js` file up-to-date when the -# unfile helpers change. -generated_file_test( - name = "runfiles_checked_in", - src = "index.cjs", - generated = "index_bundled.js", -) - # END-INTERNAL filegroup(
diff --git a/internal/runfiles/rollup.config.js b/internal/runfiles/rollup.config.js deleted file mode 100755 index b59bded..0000000 --- a/internal/runfiles/rollup.config.js +++ /dev/null
@@ -1,17 +0,0 @@ -const commonjs = require('@rollup/plugin-commonjs'); -const {nodeResolve} = require('@rollup/plugin-node-resolve'); - -module.exports = { - output: { - // Since we check-in the bundle, add a comment that disables - // clang-format for the checked-in file. - banner: '// clang-format off', - }, - - plugins: [ - nodeResolve({preferBuiltins: true}), - // The runfile helpers use a dynamic import for loading the - // NodeJS patch script. We want to preserve such dynamic imports. - commonjs({ignoreDynamicRequires: true}), - ], -};
diff --git a/npm_deps.bzl b/npm_deps.bzl index cf3cfd5..318ba1a 100644 --- a/npm_deps.bzl +++ b/npm_deps.bzl
@@ -545,9 +545,3 @@ # TODO: fix tests when this flag is flipped exports_directories_only = False, ) - - yarn_install( - name = "rollup_test_multi_linker_deps", - package_json = "//packages/rollup/test/multi_linker:package.json", - yarn_lock = "//packages/rollup/test/multi_linker:yarn.lock", - )
diff --git a/packages/index.bzl b/packages/index.bzl index 5ed46bd..fc4821b 100644 --- a/packages/index.bzl +++ b/packages/index.bzl
@@ -17,7 +17,6 @@ NPM_PACKAGES = ["@bazel/%s" % pkg for pkg in [ "create", - "rollup", "runfiles", "typescript", "worker",
diff --git a/packages/node-patches/BUILD.bazel b/packages/node-patches/BUILD.bazel index a3b7245..b4886a5 100644 --- a/packages/node-patches/BUILD.bazel +++ b/packages/node-patches/BUILD.bazel
@@ -14,7 +14,7 @@ load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_test") load("@npm_node_patches//typescript:index.bzl", "tsc") -load("//packages/rollup:index.bzl", "rollup_bundle") +load("//internal/common:copy_to_bin.bzl", "copy_to_bin") package(default_visibility = ["//:__subpackages__"]) @@ -68,13 +68,7 @@ ], ) -rollup_bundle( +copy_to_bin( name = "bundle", - srcs = js, - config_file = "rollup.config.js", - entry_point = "register.js", - format = "cjs", - sourcemap = "false", - tags = ["fix-windows"], - deps = ["@npm//@rollup/plugin-commonjs"], -) + srcs = ["bundle.cjs"], +) \ No newline at end of file
diff --git a/packages/node-patches/bundle.cjs b/packages/node-patches/bundle.cjs new file mode 100644 index 0000000..239bb5f --- /dev/null +++ b/packages/node-patches/bundle.cjs
@@ -0,0 +1,677 @@ +// clang-format off +'use strict'; + +var path = require('path'); +var util = require('util'); +var fs$1 = require('fs'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var path__default = /*#__PURE__*/_interopDefaultLegacy(path); +var util__default = /*#__PURE__*/_interopDefaultLegacy(util); +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$1); + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function createCommonjsModule(fn) { + var module = { exports: {} }; + return fn(module, module.exports), module.exports; +} + +var fs = createCommonjsModule(function (module, exports) { +/** + * @license + * Copyright 2019 The Bazel Authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __asyncValues = (commonjsGlobal && commonjsGlobal.__asyncValues) || function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +}; +var __await = (commonjsGlobal && commonjsGlobal.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }; +var __asyncGenerator = (commonjsGlobal && commonjsGlobal.__asyncGenerator) || function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.escapeFunction = exports.isOutPath = exports.patcher = void 0; + + +// using require here on purpose so we can override methods with any +// also even though imports are mutable in typescript the cognitive dissonance is too high because +// es modules + +// tslint:disable-next-line:no-any +const patcher = (fs = fs__default['default'], roots) => { + fs = fs || fs__default['default']; + roots = roots || []; + roots = roots.filter(root => fs.existsSync(root)); + if (!roots.length) { + if (process.env.VERBOSE_LOGS) { + console.error('fs patcher called without any valid root paths ' + __filename); + } + return; + } + const origRealpath = fs.realpath.bind(fs); + const origRealpathNative = fs.realpath.native; + const origLstat = fs.lstat.bind(fs); + const origStat = fs.stat.bind(fs); + const origStatSync = fs.statSync.bind(fs); + const origReadlink = fs.readlink.bind(fs); + const origLstatSync = fs.lstatSync.bind(fs); + const origRealpathSync = fs.realpathSync.bind(fs); + const origRealpathSyncNative = fs.realpathSync.native; + const origReadlinkSync = fs.readlinkSync.bind(fs); + const origReaddir = fs.readdir.bind(fs); + const origReaddirSync = fs.readdirSync.bind(fs); + const { isEscape } = exports.escapeFunction(roots); + // tslint:disable-next-line:no-any + fs.lstat = (...args) => { + let cb = args.length > 1 ? args[args.length - 1] : undefined; + // preserve error when calling function without required callback. + if (cb) { + cb = once(cb); + args[args.length - 1] = (err, stats) => { + if (err) + return cb(err); + path__default['default'].resolve(args[0]); + if (!stats.isSymbolicLink()) { + return cb(null, stats); + } + return origReadlink(args[0], (err, str) => { + if (err) { + if (err.code === 'ENOENT') { + return cb(null, stats); + } + else if (err.code === 'EINVAL') { + // readlink only returns einval when the target is not a link. + // so if we found a link and it's no longer a link someone raced file system + // modifications. we return the error but a strong case could be made to return the + // original stat. + return cb(err); + } + else { + // some other file system related error. + return cb(err); + } + } + str = path__default['default'].resolve(path__default['default'].dirname(args[0]), str); + if (isEscape(str, args[0])) { + // if it's an out link we have to return the original stat. + return origStat(args[0], (err, plainStat) => { + if (err && err.code === 'ENOENT') { + // broken symlink. return link stats. + return cb(null, stats); + } + cb(err, plainStat); + }); + } + // its a symlink and its inside of the root. + cb(null, stats); + }); + }; + } + origLstat(...args); + }; + // tslint:disable-next-line:no-any + fs.realpath = (...args) => { + let cb = args.length > 1 ? args[args.length - 1] : undefined; + if (cb) { + cb = once(cb); + args[args.length - 1] = (err, str) => { + if (err) + return cb(err); + if (isEscape(str, args[0])) { + cb(null, path__default['default'].resolve(args[0])); + } + else { + cb(null, str); + } + }; + } + origRealpath(...args); + }; + fs.realpath.native = + (...args) => { + let cb = args.length > 1 ? args[args.length - 1] : undefined; + if (cb) { + cb = once(cb); + args[args.length - 1] = (err, str) => { + if (err) + return cb(err); + if (isEscape(str, args[0])) { + cb(null, path__default['default'].resolve(args[0])); + } + else { + cb(null, str); + } + }; + } + origRealpathNative(...args); + }; + // tslint:disable-next-line:no-any + fs.readlink = (...args) => { + let cb = args.length > 1 ? args[args.length - 1] : undefined; + if (cb) { + cb = once(cb); + args[args.length - 1] = (err, str) => { + args[0] = path__default['default'].resolve(args[0]); + if (str) + str = path__default['default'].resolve(path__default['default'].dirname(args[0]), str); + if (err) + return cb(err); + if (isEscape(str, args[0])) { + const e = new Error('EINVAL: invalid argument, readlink \'' + args[0] + '\''); + // tslint:disable-next-line:no-any + e.code = 'EINVAL'; + // if its not supposed to be a link we have to trigger an EINVAL error. + return cb(e); + } + cb(null, str); + }; + } + origReadlink(...args); + }; + // tslint:disable-next-line:no-any + fs.lstatSync = (...args) => { + const stats = origLstatSync(...args); + const linkPath = path__default['default'].resolve(args[0]); + if (!stats.isSymbolicLink()) { + return stats; + } + let linkTarget; + try { + linkTarget = path__default['default'].resolve(path__default['default'].dirname(args[0]), origReadlinkSync(linkPath)); + } + catch (e) { + if (e.code === 'ENOENT') { + return stats; + } + throw e; + } + if (isEscape(linkTarget, linkPath)) { + try { + return origStatSync(...args); + } + catch (e) { + // enoent means we have a broken link. + // broken links that escape are returned as lstat results + if (e.code !== 'ENOENT') { + throw e; + } + } + } + return stats; + }; + // tslint:disable-next-line:no-any + fs.realpathSync = (...args) => { + const str = origRealpathSync(...args); + if (isEscape(str, args[0])) { + return path__default['default'].resolve(args[0]); + } + return str; + }; + // tslint:disable-next-line:no-any + fs.realpathSync.native = (...args) => { + const str = origRealpathSyncNative(...args); + if (isEscape(str, args[0])) { + return path__default['default'].resolve(args[0]); + } + return str; + }; + // tslint:disable-next-line:no-any + fs.readlinkSync = (...args) => { + args[0] = path__default['default'].resolve(args[0]); + const str = path__default['default'].resolve(path__default['default'].dirname(args[0]), origReadlinkSync(...args)); + if (isEscape(str, args[0]) || str === args[0]) { + const e = new Error('EINVAL: invalid argument, readlink \'' + args[0] + '\''); + // tslint:disable-next-line:no-any + e.code = 'EINVAL'; + throw e; + } + return str; + }; + // tslint:disable-next-line:no-any + fs.readdir = (...args) => { + const p = path__default['default'].resolve(args[0]); + let cb = args[args.length - 1]; + if (typeof cb !== 'function') { + // this will likely throw callback required error. + return origReaddir(...args); + } + cb = once(cb); + args[args.length - 1] = (err, result) => { + if (err) + return cb(err); + // user requested withFileTypes + if (result[0] && result[0].isSymbolicLink) { + Promise.all(result.map((v) => handleDirent(p, v))) + .then(() => { + cb(null, result); + }) + .catch(err => { + cb(err); + }); + } + else { + // string array return for readdir. + cb(null, result); + } + }; + origReaddir(...args); + }; + // tslint:disable-next-line:no-any + fs.readdirSync = (...args) => { + const res = origReaddirSync(...args); + const p = path__default['default'].resolve(args[0]); + // tslint:disable-next-line:no-any + res.forEach((v) => { + handleDirentSync(p, v); + }); + return res; + }; + // i need to use this twice in bodt readdor and readdirSync. maybe in fs.Dir + // tslint:disable-next-line:no-any + function patchDirent(dirent, stat) { + // add all stat is methods to Dirent instances with their result. + for (const i in stat) { + if (i.indexOf('is') === 0 && typeof stat[i] === 'function') { + // + const result = stat[i](); + if (result) + dirent[i] = () => true; + else + dirent[i] = () => false; + } + } + } + if (fs.opendir) { + const origOpendir = fs.opendir.bind(fs); + // tslint:disable-next-line:no-any + fs.opendir = (...args) => { + let cb = args[args.length - 1]; + // if this is not a function opendir should throw an error. + // we call it so we don't have to throw a mock + if (typeof cb === 'function') { + cb = once(cb); + args[args.length - 1] = async (err, dir) => { + try { + cb(null, await handleDir(dir)); + } + catch (e) { + cb(e); + } + }; + origOpendir(...args); + } + else { + return origOpendir(...args).then((dir) => { + return handleDir(dir); + }); + } + }; + } + async function handleDir(dir) { + const p = path__default['default'].resolve(dir.path); + const origIterator = dir[Symbol.asyncIterator].bind(dir); + // tslint:disable-next-line:no-any + const origRead = dir.read.bind(dir); + dir[Symbol.asyncIterator] = function () { + return __asyncGenerator(this, arguments, function* () { + var e_1, _a; + try { + for (var _b = __asyncValues(origIterator()), _c; _c = yield __await(_b.next()), !_c.done;) { + const entry = _c.value; + yield __await(handleDirent(p, entry)); + yield yield __await(entry); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b)); + } + finally { if (e_1) throw e_1.error; } + } + }); + }; + // tslint:disable-next-line:no-any + dir.read = async (...args) => { + if (typeof args[args.length - 1] === 'function') { + const cb = args[args.length - 1]; + args[args.length - 1] = async (err, entry) => { + cb(err, entry ? await handleDirent(p, entry) : null); + }; + origRead(...args); + } + else { + const entry = await origRead(...args); + if (entry) { + await handleDirent(p, entry); + } + return entry; + } + }; + // tslint:disable-next-line:no-any + const origReadSync = dir.readSync.bind(dir); + // tslint:disable-next-line:no-any + dir.readSync = () => { + return handleDirentSync(p, origReadSync()); + }; + return dir; + } + let handleCounter = 0; + function handleDirent(p, v) { + handleCounter++; + return new Promise((resolve, reject) => { + if (fs.DEBUG) + console.error(handleCounter + ' opendir: found link? ', path__default['default'].join(p, v.name), v.isSymbolicLink()); + if (!v.isSymbolicLink()) { + return resolve(v); + } + const linkName = path__default['default'].join(p, v.name); + origReadlink(linkName, (err, target) => { + if (err) { + return reject(err); + } + if (fs.DEBUG) + console.error(handleCounter + ' opendir: escapes? [target]', path__default['default'].resolve(target), '[link] ' + linkName, isEscape(path__default['default'].resolve(target), linkName), roots); + if (!isEscape(path__default['default'].resolve(target), linkName)) { + return resolve(v); + } + fs.stat(target, (err, stat) => { + if (err) { + if (err.code === 'ENOENT') { + if (fs.DEBUG) + console.error(handleCounter + ' opendir: broken link! resolving to link ', path__default['default'].resolve(target)); + // this is a broken symlink + // even though this broken symlink points outside of the root + // we'll return it. + // the alternative choice here is to omit it from the directory listing altogether + // this would add complexity because readdir output would be different than readdir + // withFileTypes unless readdir was changed to match. if readdir was changed to match + // it's performance would be greatly impacted because we would always have to use the + // withFileTypes version which is slower. + return resolve(v); + } + // transient fs related error. busy etc. + return reject(err); + } + if (fs.DEBUG) + console.error(handleCounter + ' opendir: patching dirent to look like it\'s target', path__default['default'].resolve(target)); + // add all stat is methods to Dirent instances with their result. + patchDirent(v, stat); + v.isSymbolicLink = () => false; + resolve(v); + }); + }); + }); + } + function handleDirentSync(p, v) { + if (v && v.isSymbolicLink) { + if (v.isSymbolicLink()) { + // any errors thrown here are valid. things like transient fs errors + const target = path__default['default'].resolve(p, origReadlinkSync(path__default['default'].join(p, v.name))); + if (isEscape(target, path__default['default'].join(p, v.name))) { + // Dirent exposes file type so if we want to hide that this is a link + // we need to find out if it's a file or directory. + v.isSymbolicLink = () => false; + // tslint:disable-next-line:no-any + const stat = origStatSync(target); + // add all stat is methods to Dirent instances with their result. + patchDirent(v, stat); + } + } + } + } + /** + * patch fs.promises here. + * + * this requires a light touch because if we trigger the getter on older nodejs versions + * it will log an experimental warning to stderr + * + * `(node:62945) ExperimentalWarning: The fs.promises API is experimental` + * + * this api is available as experimental without a flag so users can access it at any time. + */ + const promisePropertyDescriptor = Object.getOwnPropertyDescriptor(fs, 'promises'); + if (promisePropertyDescriptor) { + // tslint:disable-next-line:no-any + const promises = {}; + promises.lstat = util__default['default'].promisify(fs.lstat); + // NOTE: node core uses the newer realpath function fs.promises.native instead of fs.realPath + promises.realpath = util__default['default'].promisify(fs.realpath.native); + promises.readlink = util__default['default'].promisify(fs.readlink); + promises.readdir = util__default['default'].promisify(fs.readdir); + if (fs.opendir) + promises.opendir = util__default['default'].promisify(fs.opendir); + // handle experimental api warnings. + // only applies to version of node where promises is a getter property. + if (promisePropertyDescriptor.get) { + const oldGetter = promisePropertyDescriptor.get.bind(fs); + const cachedPromises = {}; + promisePropertyDescriptor.get = () => { + const _promises = oldGetter(); + Object.assign(cachedPromises, _promises, promises); + return cachedPromises; + }; + Object.defineProperty(fs, 'promises', promisePropertyDescriptor); + } + else { + // api can be patched directly + Object.assign(fs.promises, promises); + } + } +}; +exports.patcher = patcher; +function isOutPath(root, str) { + if (!root) + return true; + let strParts = str.split(path__default['default'].sep); + let rootParts = root.split(path__default['default'].sep); + let i = 0; + for (; i < rootParts.length && i < strParts.length; i++) { + if (rootParts[i] === strParts[i] || rootParts[i] === '*') { + continue; + } + break; + } + return i < rootParts.length; +} +exports.isOutPath = isOutPath; +const escapeFunction = (roots) => { + // ensure roots are always absolute + roots = roots.map(root => path__default['default'].resolve(root)); + function isEscape(linkTarget, linkPath) { + if (!path__default['default'].isAbsolute(linkPath)) { + linkPath = path__default['default'].resolve(linkPath); + } + if (!path__default['default'].isAbsolute(linkTarget)) { + linkTarget = path__default['default'].resolve(linkTarget); + } + for (const root of roots) { + if (isOutPath(root, linkTarget) && !isOutPath(root, linkPath)) { + // don't escape out of the root + return true; + } + } + return false; + } + return { isEscape, isOutPath }; +}; +exports.escapeFunction = escapeFunction; +function once(fn) { + let called = false; + return (...args) => { + if (called) + return; + called = true; + let err = false; + try { + fn(...args); + } + catch (_e) { + err = _e; + } + // blow the stack to make sure this doesn't fall into any unresolved promise contexts + if (err) { + setImmediate(() => { + throw err; + }); + } + }; +} +}); + +var subprocess = createCommonjsModule(function (module, exports) { +Object.defineProperty(exports, "__esModule", { value: true }); +exports.patcher = void 0; +// this does not actually patch child_process +// but adds support to ensure the registered loader is included in all nested executions of nodejs. + + +const patcher = (requireScriptName, nodeDir) => { + requireScriptName = path__default['default'].resolve(requireScriptName); + nodeDir = nodeDir || path__default['default'].join(path__default['default'].dirname(requireScriptName), '_node_bin'); + const file = path__default['default'].basename(requireScriptName); + try { + fs__default['default'].mkdirSync(nodeDir, { recursive: true }); + } + catch (e) { + // with node versions that don't have recursive mkdir this may throw an error. + if (e.code !== 'EEXIST') { + throw e; + } + } + if (process.platform == 'win32') { + const nodeEntry = path__default['default'].join(nodeDir, 'node.bat'); + if (!fs__default['default'].existsSync(nodeEntry)) { + fs__default['default'].writeFileSync(nodeEntry, `@if not defined DEBUG_HELPER @ECHO OFF +set NP_SUBPROCESS_NODE_DIR=${nodeDir} +set Path=${nodeDir};%Path% +"${process.execPath}" --require "${requireScriptName}" %* +`); + } + } + else { + const nodeEntry = path__default['default'].join(nodeDir, 'node'); + if (!fs__default['default'].existsSync(nodeEntry)) { + fs__default['default'].writeFileSync(nodeEntry, `#!/bin/bash +export NP_SUBPROCESS_NODE_DIR="${nodeDir}" +export PATH="${nodeDir}":\$PATH +if [[ ! "\${@}" =~ "${file}" ]]; then + exec ${process.execPath} --require "${requireScriptName}" "$@" +else + exec ${process.execPath} "$@" +fi +`, { mode: 0o777 }); + } + } + if (!process.env.PATH) { + process.env.PATH = nodeDir; + } + else if (process.env.PATH.indexOf(nodeDir + path__default['default'].delimiter) === -1) { + process.env.PATH = nodeDir + path__default['default'].delimiter + process.env.PATH; + } + // fix execPath so folks use the proxy node + if (process.platform == 'win32') ; + else { + process.argv[0] = process.execPath = path__default['default'].join(nodeDir, 'node'); + } + // replace any instances of require script in execArgv with the absolute path to the script. + // example: bazel-require-script.js + process.execArgv.map(v => { + if (v.indexOf(file) > -1) { + return requireScriptName; + } + return v; + }); +}; +exports.patcher = patcher; +}); + +var src = createCommonjsModule(function (module, exports) { +Object.defineProperty(exports, "__esModule", { value: true }); +exports.subprocess = exports.fs = void 0; +/** + * @license + * Copyright 2019 The Bazel Authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +exports.fs = fs.patcher; +exports.subprocess = subprocess.patcher; +}); + +/** + * @license + * Copyright 2019 The Bazel Authors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @fileoverview Description of this file. + */ + +const { BAZEL_PATCH_ROOTS, NP_SUBPROCESS_NODE_DIR, VERBOSE_LOGS } = process.env; +if (BAZEL_PATCH_ROOTS) { + const roots = BAZEL_PATCH_ROOTS ? BAZEL_PATCH_ROOTS.split(',') : []; + if (VERBOSE_LOGS) + console.error(`bazel node patches enabled. roots: ${roots} symlinks in these directories will not escape`); + const fs = fs__default['default']; + src.fs(fs, roots); +} +else if (VERBOSE_LOGS) { + console.error(`bazel node patches disabled. set environment BAZEL_PATCH_ROOTS`); +} +src.subprocess(__filename, NP_SUBPROCESS_NODE_DIR); + +var register = { + +}; + +module.exports = register;
diff --git a/packages/node-patches/rollup.config.js b/packages/node-patches/rollup.config.js deleted file mode 100644 index e2ada67..0000000 --- a/packages/node-patches/rollup.config.js +++ /dev/null
@@ -1,8 +0,0 @@ -const commonjs = require('@rollup/plugin-commonjs'); - -module.exports = { - output: { - banner: '// clang-format off', - }, - plugins: [commonjs()], -};
diff --git a/packages/rollup/BUILD.bazel b/packages/rollup/BUILD.bazel deleted file mode 100644 index 72c3f27..0000000 --- a/packages/rollup/BUILD.bazel +++ /dev/null
@@ -1,73 +0,0 @@ -# Copyright 2017 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -load("@bazel_skylib//:bzl_library.bzl", "bzl_library") -load("@build_bazel_rules_nodejs//:tools/defaults.bzl", "codeowners", "pkg_npm") -load("@build_bazel_rules_nodejs//tools/stardoc:index.bzl", "stardoc") -load("//third_party/github.com/bazelbuild/bazel-skylib:rules/copy_file.bzl", "copy_file") - -package(default_visibility = ["//visibility:public"]) - -codeowners( - teams = ["@jbedard"], -) - -exports_files([ - "rollup.config.js", - "index.js", -]) - -bzl_library( - name = "bzl", - srcs = glob(["*.bzl"]), - deps = [ - "@bazel_skylib//lib:types", - "@build_bazel_rules_nodejs//:bzl", - "@build_bazel_rules_nodejs//internal/common:bzl", - "@build_bazel_rules_nodejs//internal/linker:bzl", - "@rules_nodejs//nodejs:bzl", - ], -) - -stardoc( - name = "docs", - testonly = True, - out = "README.md", - input = ":index.bzl", - tags = ["fix-windows"], - deps = [":bzl"], -) - -copy_file( - name = "npm_version_check", - src = "//internal:npm_version_check.js", - out = ":npm_version_check.js", -) - -pkg_npm( - name = "npm_package", - package_name = "@bazel/rollup", - srcs = [ - "index.bzl", - "index.js", - "package.json", - "rollup.config.js", - "rollup_bundle.bzl", - ], - build_file_content = """exports_files(["rollup.config.js"])""", - deps = [ - ":README.md", - ":npm_version_check", - ], -)
diff --git a/packages/rollup/bin/BUILD.bazel b/packages/rollup/bin/BUILD.bazel deleted file mode 100644 index 485ec92..0000000 --- a/packages/rollup/bin/BUILD.bazel +++ /dev/null
@@ -1,17 +0,0 @@ -"""The default binaries used in our local builds - -Note that in the npm distribution, this file is absent, and will be generated on-the-fly when -the package is installed (possibly with different attribute values). -""" - -load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary") - -nodejs_binary( - name = "rollup-worker", - data = [ - "//packages/worker:library", - "@npm//rollup", - ], - entry_point = "//packages/rollup:index.js", - visibility = ["//visibility:public"], -)
diff --git a/packages/rollup/index.bzl b/packages/rollup/index.bzl deleted file mode 100644 index dec64a5..0000000 --- a/packages/rollup/index.bzl +++ /dev/null
@@ -1,204 +0,0 @@ -# Copyright 2019 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -# Rollup rules for Bazel - -The Rollup rules run the [rollup.js](https://rollupjs.org/) bundler with Bazel. - -## Installation - -Add the `@bazel/rollup` npm package to your `devDependencies` in `package.json`. (`rollup` itself should also be included in `devDependencies`, unless you plan on providing it via a custom target.) - -### Installing with user-managed dependencies - -If you didn't use the `yarn_install` or `npm_install` rule, you'll have to declare a rule in your root `BUILD.bazel` file to execute rollup: - -```python -# Create a rollup rule to use in rollup_bundle#rollup_bin -# attribute when using user-managed dependencies -nodejs_binary( - name = "rollup_bin", - entry_point = "//:node_modules/rollup/bin/rollup", - # Point bazel to your node_modules to find the entry point - data = ["//:node_modules"], -) -``` - -## Usage - -The `rollup_bundle` rule is used to invoke Rollup on some JavaScript inputs. -The API docs appear [below](#rollup_bundle). - -Typical example: -```python -load("@npm//@bazel/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "bundle", - srcs = ["dependency.js"], - entry_point = "input.js", - config_file = "rollup.config.js", -) -``` - -Note that the command-line options set by Bazel override what appears in the rollup config file. -This means that typically a single `rollup.config.js` can contain settings for your whole repo, -and multiple `rollup_bundle` rules can share the configuration. - -Thus, setting options that Bazel controls will have no effect, e.g. - -```javascript -module.exports = { - output: { file: 'this_is_ignored.js' }, -} -``` - -### Output types - -You must determine ahead of time whether Rollup will write a single file or a directory. -Rollup's CLI has the same behavior, forcing you to pick `--output.file` or `--output.dir`. - -Writing a directory is used when you have dynamic imports which cause code-splitting, or if you -provide multiple entry points. Use the `output_dir` attribute to specify that you want a -directory output. - -Each `rollup_bundle` rule produces only one output by running the rollup CLI a single time. -To get multiple output formats, you can wrap the rule with a macro or list comprehension, e.g. - -```python -[ - rollup_bundle( - name = "bundle.%s" % format, - entry_point = "foo.js", - format = format, - ) - for format in [ - "cjs", - "umd", - ] -] -``` - -This will produce one output per requested format. - -### Stamping - -You can stamp the current version control info into the output by writing some code in your rollup config. -See the [stamping documentation](stamping). - -By passing the `--stamp` option to Bazel, two additional input files will be readable by Rollup. - -1. The variable `bazel_version_file` will point to `bazel-out/volatile-status.txt` which contains -statuses that change frequently; such changes do not cause a re-build of the rollup_bundle. -2. The variable `bazel_info_file` will point to `bazel-out/stable-status.txt` file which contains -statuses that stay the same; any changed values will cause rollup_bundle to rebuild. - -Both `bazel_version_file` and `bazel_info_file` will be `undefined` if the build is run without `--stamp`. - -> Note that under `--stamp`, only the bundle is re-built, but not the compilation steps that produced the inputs. -> This avoids a slow cascading re-build of a whole tree of actions. - -To use these files, you write JS code in your `rollup.config.js` to read from the status files and parse the lines. -Each line is a space-separated key/value pair. - -```javascript -/** -* The status files are expected to look like -* BUILD_SCM_HASH 83c699db39cfd74526cdf9bebb75aa6f122908bb -* BUILD_SCM_LOCAL_CHANGES true -* STABLE_BUILD_SCM_VERSION 6.0.0-beta.6+12.sha-83c699d.with-local-changes -* BUILD_TIMESTAMP 1520021990506 -* -* Parsing regex is created based on Bazel's documentation describing the status file schema: -* The key names can be anything but they may only use upper case letters and underscores. The -* first space after the key name separates it from the value. The value is the rest of the line -* (including additional whitespaces). -* -* @param {string} p the path to the status file -* @returns a two-dimensional array of key/value pairs -*/ -function parseStatusFile(p) { - if (!p) return []; - const results = {}; - const statusFile = require('fs').readFileSync(p, {encoding: 'utf-8'}); - for (const match of `\n${statusFile}`.matchAll(/^([A-Z_]+) (.*)/gm)) { - // Lines which go unmatched define an index value of `0` and should be skipped. - if (match.index === 0) { - continue; - } - results[match[1]] = match[2]; - } - return results; -} - -// This undefined variable will be replaced with the full path during the build. -const statuses = parseStatusFile(bazel_version_file); -// Parse the stamp file produced by Bazel from the version control system -let version = '<unknown>'; -// Don't assume BUILD_SCM_VERSION exists -if (statuses['BUILD_SCM_VERSION']) { - version = 'v' + statuses['BUILD_SCM_VERSION']; - if (DEBUG) { - version += '_debug'; - } -} -``` - -### Debug and Opt builds - -When you use `--compilation_mode=dbg`, Bazel produces a distinct output-tree in `bazel-out/[arch]-dbg/bin`. -Code in your `rollup.config.js` can look in the environment to detect if a debug build is being performed, -and include extra developer information in the bundle that you wouldn't normally ship to production. - -Similarly, `--compilation_mode=opt` is Bazel's signal to perform extra optimizations. -You could use this value to perform extra production-only optimizations. - -For example you could define a constant for enabling Debug: - -```javascript -const DEBUG = process.env['COMPILATION_MODE'] === 'dbg'; -``` - -and configure Rollup differently when `DEBUG` is `true` or `false`. - -### Increasing Heap memory for rollup - -The `rollup_bin` attribute allows you to customize the rollup.js program we execute, -so you can use `nodejs_binary` to construct your own. - -> You can always call `bazel query --output=build [default rollup_bin]` to see what -> the default definition looks like, then copy-paste from there to be sure yours -> matches. - -```python -nodejs_binary( - name = "rollup_more_mem", - data = ["@npm//rollup:rollup"], - entry_point = "@npm//:node_modules/rollup/dist/bin/rollup", - templated_args = [ - "--node_options=--max-old-space-size=<SOME_SIZE>", - ], -) - -rollup_bundle( - ... - rollup_bin = ":rollup_more_mem", -) -``` -""" - -load(":rollup_bundle.bzl", _rollup_bundle = "rollup_bundle") - -rollup_bundle = _rollup_bundle
diff --git a/packages/rollup/index.js b/packages/rollup/index.js deleted file mode 100644 index ff67d2d..0000000 --- a/packages/rollup/index.js +++ /dev/null
@@ -1,229 +0,0 @@ -/** - * @license - * Copyright 2020 The Bazel Authors. All rights reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const path = require('path'); -const rollup = require('rollup'); -const loadConfigFile = require('rollup/dist/loadConfigFile'); -const crypto = require('crypto') -const worker = require('@bazel/worker'); - -const MNEMONIC = 'Rollup'; -const PID = process.pid; - -// Store the cache forever to re-use on each build -let cacheMap = Object.create(null); - -// Generate a unique cache ID based on the given json data -function computeCacheKey(cacheKeyData) { - const hash = crypto.createHash('sha256'); - const hashContent = JSON.stringify(cacheKeyData); - return hash.update(hashContent).digest('hex'); -} - -async function runRollup(cacheKeyData, inputOptions, outputOptions) { - const cacheKey = computeCacheKey(cacheKeyData); - - let cache = cacheMap[cacheKey]; - - const rollupStartTime = Date.now(); - - const bundle = await rollup.rollup({...inputOptions, cache}); - - const rollupEndTime = Date.now(); - worker.debug( - `${MNEMONIC}[${PID}][${cacheKey}].rollup()`, (rollupEndTime - rollupStartTime) / 1000); - - cacheMap[cacheKey] = bundle.cache; - - try { - await bundle.write(outputOptions); - } catch (e) { - worker.log(e); - return false; - } - - const bundleEndTime = Date.now(); - worker.debug(`${MNEMONIC}[${PID}][${cacheKey}].write()`, (bundleEndTime - rollupEndTime) / 1000); - - return true; -} - -// Run rollup, will use + re-populate the cache -// Essentially the same as the rollup CLI but using bazel APIs -// for CLI arguments and FS watching -// See: https://github.com/rollup/rollup/blob/v2.23.1/cli/run/index.ts#L11 -async function runRollupBundler(args /*, inputs */) { - const {inputOptions, outputOptions} = await parseCLIArgs(args); - - const cacheKeyData = [ - inputOptions.input, - - // Include changes to externals in the cache key because rollup currently - // ignores such changes when using the caching API - // See https://github.com/rollup/rollup/issues/3874 - inputOptions.external - ]; - - return runRollup(cacheKeyData, inputOptions, outputOptions); -} - -// Processing of --environment CLI options into environment vars -// https://github.com/rollup/rollup/blob/v1.31.0/cli/run/index.ts#L50-L57 -function extractEnvironmentVariables(vars) { - vars.split(',').forEach(pair => { - const [key, ...value] = pair.split(':'); - if (value.length) { - process.env[key] = value.join(':'); - } else { - process.env[key] = String(true); - } - }); -} - -// Parse a subset of supported CLI arguments required for the rollup_bundle rule API. -// Returns input/outputOptions for the rollup.bundle/write() API -// input: https://rollupjs.org/guide/en/#inputoptions-object -// output: https://rollupjs.org/guide/en/#outputoptions-object -async function parseCLIArgs(args) { - // Options which the CLI args or config file can override - const defaultInputOptions = { - onwarn(...warnArgs) { - worker.log(...warnArgs); - }, - }; - - // Options which can override the config file - let inputOptions = {}; - - let outputOptions = {}; - - let configFile = null; - - // Input files to rollup - let inputs = []; - - // Followed by suppported rollup CLI options - for (let i = 0; i < args.length; i++) { - const arg = args[i]; - - // Non-option is assumed to be an input file - if (!arg.startsWith('--')) { - inputs.push(arg); - continue; - } - - const option = arg.slice(2); - switch (option) { - case 'config': - configFile = path.resolve(args[++i]); - break; - - case 'silent': - inputOptions.onwarn = () => {}; - break; - - case 'format': - case 'output.dir': - case 'output.file': - case 'sourcemap': - outputOptions[option.replace('output.', '')] = args[++i]; - break; - - case 'preserveSymlinks': - inputOptions[option] = true; - break; - - // Common rollup CLI args, but not required for use - case 'environment': - extractEnvironmentVariables(args[++i]); - break; - - default: - throw new Error(`${MNEMONIC}: invalid or unsupported argument ${arg}`); - } - } - - // If outputting a directory then rollup_bundle.bzl passed a series - // of name=path files as the input. - // TODO: do some not have the =? - if (outputOptions.dir) { - inputs = inputs.reduce((m, nameInput) => { - const [name, input] = nameInput.split('=', 2); - m[name] = input; - return m; - }, {}); - } - - // Additional options passed via config file - if (configFile) { - const {options, warnings} = await loadConfigFile(configFile); - - // Flush any config file warnings to stderr - warnings.flush(); - - // Does NOT support (unlike rollup CLI): - // * multiple configs for multiple outputs - if (options.length !== 1) { - throw new Error('Array configs unsupported'); - } - - const config = options[0]; - - if (config.output) { - outputOptions = {...config.output[0], ...outputOptions}; - } - - inputOptions = {...config, ...inputOptions}; - - // Delete from our copied inputOptions, not the config which - // may be external and persisted across runs - delete inputOptions.output; - } - - // Provide default inputOptions which can be overwritten - inputOptions = {...defaultInputOptions, ...inputOptions}; - - // The inputs are the rule entry_point[s] - inputOptions.input = inputs; - - return {inputOptions, outputOptions}; -} - -async function main(args) { - // Bazel will pass a special argument to the program when it's running us as a worker - if (worker.runAsWorker(args)) { - worker.log(`Running ${MNEMONIC} as a Bazel worker`); - await worker.runWorkerLoop(runRollupBundler); - } else { - // Running standalone so stdout is available as usual - console.log(`Running ${MNEMONIC} as a standalone process`); - console.error( - `Started a new process to perform this action. Your build might be misconfigured, try - --strategy=${MNEMONIC}=worker`); - - // Parse the options from the bazel-supplied options file. - // The first argument to the program is prefixed with '@' - // because Bazel does that for param files. Strip it first. - const paramFile = process.argv[2].replace(/^@/, ''); - const args = require('fs').readFileSync(paramFile, 'utf-8').trim().split('\n'); - - return (await runRollupBundler(args)) ? 0 : 1; - } -} - -if (require.main == module) { - (async () => process.exitCode = await main(process.argv.slice(2)))(); -} \ No newline at end of file
diff --git a/packages/rollup/package.json b/packages/rollup/package.json deleted file mode 100644 index 42c390b..0000000 --- a/packages/rollup/package.json +++ /dev/null
@@ -1,30 +0,0 @@ -{ - "name": "@bazel/rollup", - "dependencies": { - "@bazel/worker": "0.0.0-PLACEHOLDER" - }, - "peerDependencies": { - "rollup": ">=2.3.0 <3.0.0" - }, - "description": "Run rollup.js bundler under Bazel", - "license": "Apache-2.0", - "version": "0.0.0-PLACEHOLDER", - "repository": { - "type": "git", - "url": "https://github.com/bazelbuild/rules_nodejs.git", - "directory": "packages/rollup" - }, - "bin": { - "rollup-worker": "index.js" - }, - "bugs": { - "url": "https://github.com/bazelbuild/rules_nodejs/issues" - }, - "keywords": [ - "rollup", - "bazel" - ], - "scripts": { - "postinstall": "node npm_version_check.js" - } -} \ No newline at end of file
diff --git a/packages/rollup/rollup.config.js b/packages/rollup/rollup.config.js deleted file mode 100644 index 070db90..0000000 --- a/packages/rollup/rollup.config.js +++ /dev/null
@@ -1,6 +0,0 @@ -// Note: we cannot require() any plugins here because the user may not have any installed - -module.exports = { - output: {}, - plugins: [], -};
diff --git a/packages/rollup/rollup_bundle.bzl b/packages/rollup/rollup_bundle.bzl deleted file mode 100644 index 1a6f442..0000000 --- a/packages/rollup/rollup_bundle.bzl +++ /dev/null
@@ -1,374 +0,0 @@ -"Rules for running Rollup under Bazel" - -load("@rules_nodejs//nodejs:providers.bzl", "JSModuleInfo", "STAMP_ATTR", "StampSettingInfo") -load("@build_bazel_rules_nodejs//:providers.bzl", "ExternalNpmPackageInfo", "JSEcmaScriptModuleInfo", "node_modules_aspect", "run_node") -load("@build_bazel_rules_nodejs//internal/linker:link_node_modules.bzl", "module_mappings_aspect") - -_DOC = "Runs the rollup.js CLI under Bazel." - -_ROLLUP_ATTRS = { - "args": attr.string_list( - doc = """Command line arguments to pass to Rollup. Can be used to override config file settings. - -These argument passed on the command line before arguments that are added by the rule. -Run `bazel` with `--subcommands` to see what Rollup CLI command line was invoked. - -See the <a href="https://rollupjs.org/guide/en/#command-line-flags">Rollup CLI docs</a> for a complete list of supported arguments.""", - default = [], - ), - "config_file": attr.label( - doc = """A `rollup.config.js` file - -Passed to the `--config` option, see [the config doc](https://rollupjs.org/guide/en/#configuration-files) - -If not set, a default basic Rollup config is used. -""", - allow_single_file = True, - default = "//packages/rollup:rollup.config.js", - ), - "deps": attr.label_list( - aspects = [module_mappings_aspect, node_modules_aspect], - doc = """Other libraries that are required by the code, or by the rollup.config.js""", - ), - "entry_point": attr.label( - doc = """The bundle's entry point (e.g. your main.js or app.js or index.js). - -This is just a shortcut for the `entry_points` attribute with a single output chunk named the same as the rule. - -For example, these are equivalent: - -```python -rollup_bundle( - name = "bundle", - entry_point = "index.js", -) -``` - -```python -rollup_bundle( - name = "bundle", - entry_points = { - "index.js": "bundle" - } -) -``` - -If `rollup_bundle` is used on a `ts_project`, the `rollup_bundle` rule handles selecting the correct outputs from `ts_project`. -In this case, `entry_point` can be specified as the `.ts` file and `rollup_bundle` will handle the mapping to the `.mjs` output file. - -For example: - -```python -ts_project( - name = "foo", - srcs = [ - "foo.ts", - "index.ts", - ], -) - -rollup_bundle( - name = "bundle", - deps = [ "foo" ], - entry_point = "index.ts", -) -``` -""", - allow_single_file = True, - ), - "entry_points": attr.label_keyed_string_dict( - doc = """The bundle's entry points (e.g. your main.js or app.js or index.js). - -Passed to the [`--input` option](https://github.com/rollup/rollup/blob/master/docs/999-big-list-of-options.md#input) in Rollup. - -Keys in this dictionary are labels pointing to .js entry point files. -Values are the name to be given to the corresponding output chunk. - -Either this attribute or `entry_point` must be specified, but not both. -""", - allow_files = True, - ), - "format": attr.string( - doc = """Specifies the format of the generated bundle. One of the following: - -- `amd`: Asynchronous Module Definition, used with module loaders like RequireJS -- `cjs`: CommonJS, suitable for Node and other bundlers -- `esm`: Keep the bundle as an ES module file, suitable for other bundlers and inclusion as a `<script type=module>` tag in modern browsers -- `iife`: A self-executing function, suitable for inclusion as a `<script>` tag. (If you want to create a bundle for your application, you probably want to use this.) -- `umd`: Universal Module Definition, works as amd, cjs and iife all in one -- `system`: Native format of the SystemJS loader -""", - values = ["amd", "cjs", "esm", "iife", "umd", "system"], - default = "esm", - ), - "link_workspace_root": attr.bool( - doc = """Link the workspace root to the bin_dir to support absolute requires like 'my_wksp/path/to/file'. -If source files need to be required then they can be copied to the bin_dir with copy_to_bin.""", - ), - "output_dir": attr.bool( - doc = """Whether to produce a directory output. - -We will use the [`--output.dir` option](https://github.com/rollup/rollup/blob/master/docs/999-big-list-of-options.md#outputdir) in rollup -rather than `--output.file`. - -If the program produces multiple chunks, you must specify this attribute. -Otherwise, the outputs are assumed to be a single file. -""", - ), - "rollup_bin": attr.label( - doc = "Target that executes the rollup binary", - executable = True, - cfg = "exec", - default = ( - # BEGIN-INTERNAL - "@npm" + - # END-INTERNAL - "//rollup/bin:rollup" - ), - ), - "rollup_worker_bin": attr.label( - doc = "Internal use only", - executable = True, - cfg = "exec", - default = "//packages/rollup/bin:rollup-worker", - ), - "silent": attr.bool( - doc = """Whether to execute the rollup binary with the --silent flag, defaults to False. - -Using --silent can cause rollup to [ignore errors/warnings](https://github.com/rollup/rollup/blob/master/docs/999-big-list-of-options.md#onwarn) -which are only surfaced via logging. Since bazel expects printing nothing on success, setting silent to True -is a more Bazel-idiomatic experience, however could cause rollup to drop important warnings. -""", - ), - "silent_on_success": attr.bool( - doc = """Even stronger than --silent, defaults to False. - -Since the build still emits some texted, even when passed --silent, this uses the same flag as npm_package_bin to -supress all output on sucess. -""", - ), - "sourcemap": attr.string( - doc = """Whether to produce sourcemaps. - -Passed to the [`--sourcemap` option](https://github.com/rollup/rollup/blob/master/docs/999-big-list-of-options.md#outputsourcemap") in Rollup -""", - default = "inline", - values = ["inline", "hidden", "true", "false"], - ), - "srcs": attr.label_list( - doc = """Non-entry point JavaScript source files from the workspace. - -You must not repeat file(s) passed to entry_point/entry_points. -""", - # Don't try to constrain the filenames, could be json, svg, whatever - allow_files = True, - ), - "stamp": STAMP_ATTR, - "supports_workers": attr.bool( - doc = """Experimental! Use only with caution. - -Allows you to enable the Bazel Worker strategy for this library. -When enabled, this rule invokes the "rollup_worker_bin" -worker aware binary rather than "rollup_bin".""", - default = False, - ), -} - -def _desugar_entry_point_names(name, entry_point, entry_points): - """Users can specify entry_point (sugar) or entry_points (long form). - - This function allows our code to treat it like they always used the long form. - - It also performs validation: - - exactly one of these attributes should be specified - """ - if entry_point and entry_points: - fail("Cannot specify both entry_point and entry_points") - if not entry_point and not entry_points: - fail("One of entry_point or entry_points must be specified") - if entry_point: - return [name] - return entry_points.values() - -def _desugar_entry_points(name, entry_point, entry_points, inputs): - """Like above, but used by the implementation function, where the types differ. - - It also performs validation: - - attr.label_keyed_string_dict doesn't accept allow_single_file - so we have to do validation now to be sure each key is a label resulting in one file - - It converts from dict[target: string] to dict[file: string] - """ - names = _desugar_entry_point_names(name, entry_point.label if entry_point else None, entry_points) - - if entry_point: - return {_resolve_js_input(entry_point.files.to_list()[0], inputs): names[0]} - - result = {} - for ep in entry_points.items(): - entry_point = ep[0] - name = ep[1] - f = entry_point.files.to_list() - if len(f) != 1: - fail("keys in rollup_bundle#entry_points must provide one file, but %s has %s" % (entry_point.label, len(f))) - result[_resolve_js_input(f[0], inputs)] = name - return result - -def _resolve_js_input(f, inputs): - if f.extension == "js" or f.extension == "mjs": - return f - - # look for corresponding js file in inputs - no_ext = _no_ext(f) - for i in inputs: - if i.extension == "js" or i.extension == "mjs": - if _no_ext(i) == no_ext: - return i - fail("Could not find corresponding javascript entry point for %s. Add the %s.js to your deps." % (f.path, no_ext)) - -def _rollup_outs(sourcemap, name, entry_point, entry_points, output_dir): - """Supply some labelled outputs in the common case of a single entry point""" - result = {} - entry_point_outs = _desugar_entry_point_names(name, entry_point, entry_points) - if output_dir: - # We can't declare a directory output here, because RBE will be confused, like - # com.google.devtools.build.lib.remote.ExecutionStatusException: - # INTERNAL: failed to upload outputs: failed to construct CAS files: - # failed to calculate file hash: - # read /b/f/w/bazel-out/k8-fastbuild/bin/packages/rollup/test/multiple_entry_points/chunks: is a directory - #result["chunks"] = output_dir - return {} - else: - if len(entry_point_outs) > 1: - fail("Multiple entry points require that output_dir be set") - out = entry_point_outs[0] - result[out] = out + ".js" - if sourcemap == "true": - result[out + "_map"] = "%s.map" % result[out] - return result - -def _no_ext(f): - return f.short_path[:-len(f.extension) - 1] - -def _filter_js(files): - return [f for f in files if f.extension == "js" or f.extension == "mjs"] - -def _rollup_bundle(ctx): - "Generate a rollup config file and run rollup" - - # rollup_bundle supports deps with JS providers. For each dep, - # JSEcmaScriptModuleInfo is used if found, then JSModuleInfo and finally - # the DefaultInfo files are used if the former providers are not found. - deps_depsets = [] - for dep in ctx.attr.deps: - if JSEcmaScriptModuleInfo in dep: - deps_depsets.append(dep[JSEcmaScriptModuleInfo].sources) - - if JSModuleInfo in dep: - deps_depsets.append(dep[JSModuleInfo].sources) - elif hasattr(dep, "files"): - deps_depsets.append(dep.files) - - # Also include files from npm deps as inputs. - # These deps are identified by the ExternalNpmPackageInfo provider. - if ExternalNpmPackageInfo in dep: - deps_depsets.append(dep[ExternalNpmPackageInfo].sources) - deps_inputs = depset(transitive = deps_depsets).to_list() - - inputs = _filter_js(ctx.files.entry_point) + _filter_js(ctx.files.entry_points) + ctx.files.srcs + deps_inputs - outputs = [getattr(ctx.outputs, o) for o in dir(ctx.outputs)] - - # See CLI documentation at https://rollupjs.org/guide/en/#command-line-reference - args = ctx.actions.args() - - if ctx.attr.supports_workers: - # Set to use a multiline param-file for worker mode - args.use_param_file("@%s", use_always = True) - args.set_param_file_format("multiline") - - # Add user specified arguments *before* rule supplied arguments - args.add_all(ctx.attr.args) - - # List entry point argument first to save some argv space - # Rollup doc says - # When provided as the first options, it is equivalent to not prefix them with --input - entry_points = _desugar_entry_points(ctx.label.name, ctx.attr.entry_point, ctx.attr.entry_points, inputs).items() - - # If user requests an output_dir, then use output.dir rather than output.file - if ctx.attr.output_dir: - outputs.append(ctx.actions.declare_directory(ctx.label.name)) - for entry_point in entry_points: - args.add_joined([entry_point[1], entry_point[0]], join_with = "=") - args.add_all(["--output.dir", outputs[0].path]) - else: - args.add(entry_points[0][0]) - args.add_all(["--output.file", outputs[0].path]) - - args.add_all(["--format", ctx.attr.format]) - - if ctx.attr.silent: - # Run the rollup binary with the --silent flag - args.add("--silent") - - stamp = ctx.attr.stamp[StampSettingInfo].value - - config_extension = ctx.file.config_file.extension - config = ctx.actions.declare_file("_%s.rollup_config.%s" % (ctx.label.name, config_extension)) - ctx.actions.expand_template( - template = ctx.file.config_file, - output = config, - substitutions = { - "bazel_info_file": "\"%s\"" % ctx.info_file.path if stamp else "undefined", - "bazel_version_file": "\"%s\"" % ctx.version_file.path if stamp else "undefined", - }, - ) - - args.add_all(["--config", config.path]) - inputs.append(config) - - # Prevent rollup's module resolver from hopping outside Bazel's sandbox - # When set to false, symbolic links are followed when resolving a file. - # When set to true, instead of being followed, symbolic links are treated as if the file is - # where the link is. - args.add("--preserveSymlinks") - - if (ctx.attr.sourcemap and ctx.attr.sourcemap != "false"): - args.add_all(["--sourcemap", ctx.attr.sourcemap]) - - executable = "rollup_bin" - execution_requirements = {} - - if ctx.attr.supports_workers: - executable = "rollup_worker_bin" - execution_requirements["supports-workers"] = str(int(ctx.attr.supports_workers)) - - run_node( - ctx, - progress_message = "Bundling JavaScript %s [rollup]" % outputs[0].short_path, - executable = executable, - inputs = inputs, - outputs = outputs, - arguments = [args], - mnemonic = "Rollup", - execution_requirements = execution_requirements, - env = {"COMPILATION_MODE": ctx.var["COMPILATION_MODE"]}, - link_workspace_root = ctx.attr.link_workspace_root, - silent_on_success = ctx.attr.silent_on_success, - ) - - outputs_depset = depset(outputs) - - return [ - DefaultInfo(files = outputs_depset), - JSModuleInfo( - direct_sources = outputs_depset, - sources = outputs_depset, - ), - ] - -rollup_bundle = rule( - doc = _DOC, - implementation = _rollup_bundle, - attrs = dict(_ROLLUP_ATTRS), - outputs = _rollup_outs, -)
diff --git a/packages/rollup/test/alias-mapping/BUILD.bazel b/packages/rollup/test/alias-mapping/BUILD.bazel deleted file mode 100644 index 4519a59..0000000 --- a/packages/rollup/test/alias-mapping/BUILD.bazel +++ /dev/null
@@ -1,31 +0,0 @@ -load("//:index.bzl", "generated_file_test") -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "bundle", - config_file = "rollup.config.js", - entry_point = "main.js", - sourcemap = "hidden", - deps = [ - "//packages/rollup/test/alias-mapping/module-one", - "//packages/rollup/test/alias-mapping/module-two", - "@npm//@rollup/plugin-node-resolve", - ], -) - -# rollup will put the filepath in a comment within the non-minified file, -# on different platforms this will cause the golden test to differ -# strip them here -# note that this regex doesn't strip the sourcemap URI comment -genrule( - name = "strip_bundle_comments", - srcs = ["bundle.js"], - outs = ["bundle.stripped.js"], - cmd = "cat $(location :bundle.js) | sed \"s#// .*##\" > $@", -) - -generated_file_test( - name = "bundle_test", - src = "bundle.golden.txt", - generated = "bundle.stripped.js", -)
diff --git a/packages/rollup/test/alias-mapping/bundle.golden.txt b/packages/rollup/test/alias-mapping/bundle.golden.txt deleted file mode 100644 index e817f16..0000000 --- a/packages/rollup/test/alias-mapping/bundle.golden.txt +++ /dev/null
@@ -1,7 +0,0 @@ -const getId$1 = () => 'module-one'; - -const getId = () => 'module-two'; - -var main = `Full ID: ${getId$1} - ${getId}`; - -export default main;
diff --git a/packages/rollup/test/alias-mapping/main.js b/packages/rollup/test/alias-mapping/main.js deleted file mode 100644 index 21a284e..0000000 --- a/packages/rollup/test/alias-mapping/main.js +++ /dev/null
@@ -1,4 +0,0 @@ -import {getId as m1Id} from '@alias-mapping/module-one'; -import {getId as m2Id} from '@alias-mapping/module-two'; - -export default `Full ID: ${m1Id} - ${m2Id}`;
diff --git a/packages/rollup/test/alias-mapping/module-one/BUILD.bazel b/packages/rollup/test/alias-mapping/module-one/BUILD.bazel deleted file mode 100644 index 62352b2..0000000 --- a/packages/rollup/test/alias-mapping/module-one/BUILD.bazel +++ /dev/null
@@ -1,9 +0,0 @@ -load("//internal/js_library:js_library.bzl", "js_library") - -package(default_visibility = ["//packages/rollup/test:__subpackages__"]) - -js_library( - name = "module-one", - package_name = "@alias-mapping/module-one", - srcs = [":index.js"], -)
diff --git a/packages/rollup/test/alias-mapping/module-one/index.js b/packages/rollup/test/alias-mapping/module-one/index.js deleted file mode 100644 index be8c740..0000000 --- a/packages/rollup/test/alias-mapping/module-one/index.js +++ /dev/null
@@ -1 +0,0 @@ -export const getId = () => 'module-one';
diff --git a/packages/rollup/test/alias-mapping/module-two/BUILD.bazel b/packages/rollup/test/alias-mapping/module-two/BUILD.bazel deleted file mode 100644 index 22eb9c3..0000000 --- a/packages/rollup/test/alias-mapping/module-two/BUILD.bazel +++ /dev/null
@@ -1,9 +0,0 @@ -load("//internal/js_library:js_library.bzl", "js_library") - -package(default_visibility = ["//packages/rollup/test:__subpackages__"]) - -js_library( - name = "module-two", - package_name = "@alias-mapping/module-two", - srcs = [":index.js"], -)
diff --git a/packages/rollup/test/alias-mapping/module-two/index.js b/packages/rollup/test/alias-mapping/module-two/index.js deleted file mode 100644 index 4fa9280..0000000 --- a/packages/rollup/test/alias-mapping/module-two/index.js +++ /dev/null
@@ -1 +0,0 @@ -export const getId = () => 'module-two';
diff --git a/packages/rollup/test/alias-mapping/rollup.config.js b/packages/rollup/test/alias-mapping/rollup.config.js deleted file mode 100644 index 6806c98..0000000 --- a/packages/rollup/test/alias-mapping/rollup.config.js +++ /dev/null
@@ -1,13 +0,0 @@ -import nodeResolve from '@rollup/plugin-node-resolve'; - -module.exports = { - onwarn: (warning) => { - // Always fail on warnings, assuming we don't know which are harmless. - // We can add exclusions here based on warning.code, if we discover some - // types of warning should always be ignored under bazel. - throw new Error(warning.message); - }, - plugins: [ - nodeResolve(), - ], -};
diff --git a/packages/rollup/test/code_splitting/BUILD.bazel b/packages/rollup/test/code_splitting/BUILD.bazel deleted file mode 100644 index 051712f..0000000 --- a/packages/rollup/test/code_splitting/BUILD.bazel +++ /dev/null
@@ -1,13 +0,0 @@ -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "bundle", - srcs = ["strings.js"], - config_file = "rollup.config.js", - entry_point = "input.js", - # TODO: if this isn't here, the error is - # [!] Error: You must set output.dir instead of output.file when generating multiple chunks. - # which will confuse users because it references output.dir instead of output_dir - output_dir = True, - supports_workers = True, -)
diff --git a/packages/rollup/test/code_splitting/input.js b/packages/rollup/test/code_splitting/input.js deleted file mode 100644 index 1e29b6e..0000000 --- a/packages/rollup/test/code_splitting/input.js +++ /dev/null
@@ -1 +0,0 @@ -import('./strings').then(m => {const msg = document.createElement('span'); msg.innerText = m.hello(); document.body.appendChild(msg);}); \ No newline at end of file
diff --git a/packages/rollup/test/code_splitting/rollup.config.js b/packages/rollup/test/code_splitting/rollup.config.js deleted file mode 100644 index 8ee83f6..0000000 --- a/packages/rollup/test/code_splitting/rollup.config.js +++ /dev/null
@@ -1,6 +0,0 @@ -module.exports = { - output: { - // make chunk filenames predictable - chunkFileNames: '[name].js', - } -} \ No newline at end of file
diff --git a/packages/rollup/test/code_splitting/spec.js b/packages/rollup/test/code_splitting/spec.js deleted file mode 100644 index edb3e5a..0000000 --- a/packages/rollup/test/code_splitting/spec.js +++ /dev/null
@@ -1,11 +0,0 @@ -const fs = require('fs'); -const runfiles = require(process.env['BAZEL_NODE_RUNFILES_HELPER']); - -describe('rollup code splitting', () => { - it('should produce a chunk for lazy loaded code', () => { - const chunks = runfiles.resolvePackageRelative('bundle'); - - expect(fs.existsSync(chunks + '/bundle.js')).toBeTruthy(); - expect(fs.existsSync(chunks + '/strings.js')).toBeTruthy(); - }); -});
diff --git a/packages/rollup/test/code_splitting/strings.js b/packages/rollup/test/code_splitting/strings.js deleted file mode 100644 index c0bc83e..0000000 --- a/packages/rollup/test/code_splitting/strings.js +++ /dev/null
@@ -1,3 +0,0 @@ -export function hello() { - return 'Hello World'; -}
diff --git a/packages/rollup/test/esm_config/BUILD.bazel b/packages/rollup/test/esm_config/BUILD.bazel deleted file mode 100644 index c5e8aeb..0000000 --- a/packages/rollup/test/esm_config/BUILD.bazel +++ /dev/null
@@ -1,20 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test") -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "esm_config", - config_file = "rollup.config.mjs", - entry_point = "input.js", - sourcemap = "false", - supports_workers = True, - deps = [ - # Fake test ESM package from `npm_deps.bzl`. - "@npm//test_esm_pkg", - ], -) - -generated_file_test( - name = "test", - src = "golden.js_", - generated = ":esm_config.js", -)
diff --git a/packages/rollup/test/esm_config/golden.js_ b/packages/rollup/test/esm_config/golden.js_ deleted file mode 100644 index 5ff1910..0000000 --- a/packages/rollup/test/esm_config/golden.js_ +++ /dev/null
@@ -1 +0,0 @@ -console.log('Works - test fixture');
diff --git a/packages/rollup/test/esm_config/input.js b/packages/rollup/test/esm_config/input.js deleted file mode 100644 index 5ff1910..0000000 --- a/packages/rollup/test/esm_config/input.js +++ /dev/null
@@ -1 +0,0 @@ -console.log('Works - test fixture');
diff --git a/packages/rollup/test/esm_config/rollup.config.mjs b/packages/rollup/test/esm_config/rollup.config.mjs deleted file mode 100644 index d66969a..0000000 --- a/packages/rollup/test/esm_config/rollup.config.mjs +++ /dev/null
@@ -1,7 +0,0 @@ -// Note: We want to have some actual import statements here, -// validating that ESM is actually used for this config file. -import 'test_esm_pkg'; - -export default { - plugins: [], -};
diff --git a/packages/rollup/test/integration/BUILD.bazel b/packages/rollup/test/integration/BUILD.bazel deleted file mode 100644 index 6b833c2..0000000 --- a/packages/rollup/test/integration/BUILD.bazel +++ /dev/null
@@ -1,119 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test", "nodejs_binary", "npm_package_bin") -load("//packages/rollup:index.bzl", "rollup_bundle") - -_BUNDLE_FORMATS = [ - "amd", - "cjs", - "esm", - "iife", - "umd", - "system", -] - -[ - rollup_bundle( - name = "bundle.%s" % format, - srcs = [ - "bar.js", - "some.json", - "//%s/foo:user.js" % package_name(), - ], - config_file = "rollup.config.js", - entry_point = "foo.js", - format = format, - sourcemap = "true", - supports_workers = True, - deps = [ - "//%s/fum:fumlib" % package_name(), - "//%s/foo:foo_lib" % package_name(), - "//%s/foo_a:foo_lib_a" % package_name(), - "//%s/foo_aaa:foo_lib_a_a_a" % package_name(), - "//%s/far/a/b/c" % package_name(), - "//%s/far/a" % package_name(), - "@npm//@rollup/plugin-commonjs", - "@npm//@rollup/plugin-json", - "@npm//@rollup/plugin-node-resolve", - "@npm//hello", - ], - ) - for format in _BUNDLE_FORMATS -] - -# Verify the bundle .js files -[ - generated_file_test( - name = "test_%s" % format, - src = "//%s:golden.%s.js_" % ( - package_name(), - format, - ), - generated = "bundle.%s.js" % format, - ) - for format in _BUNDLE_FORMATS -] - -nodejs_binary( - name = "sha256", - entry_point = ":sha256.js", -) - -# Verify the hash of bundle .map files -[ - npm_package_bin( - name = "bundle_%s_map_sha256" % format, - outs = ["bundle.%s.js.map.sha256" % format], - args = [ - "$(execpath :bundle.%s.js.map)" % format, - "$(execpath :bundle.%s.js.map.sha256)" % format, - ], - data = [ - # ":bundle.*.js" included as a dep as Bazel requires it for - # the "$(execpath :bundle.*.js)" location expansion to work - ":bundle.%s.js.map" % format, - # Also include ":bundle.*" as a dep so that the module mappings - # from the ":bundle.*" as propogated to ensure the linker - # handles these propogated mappings property - ":bundle.%s" % format, - ], - tool = ":sha256", - ) - for format in _BUNDLE_FORMATS -] - -[ - generated_file_test( - name = "test_%s_map_sha256" % format, - src = ":golden.%s.js.map.sha256_" % format, - generated = "bundle.%s.js.map.sha256" % format, - # TODO: fix this test on Windows as sha256 differs - tags = ["fix-windows"], - ) - for format in _BUNDLE_FORMATS -] - -npm_package_bin( - name = "bundle_umd_sha256", - outs = ["bundle.umd.js.sha256"], - args = [ - "$(execpath :bundle.umd.js)", - "$(execpath :bundle.umd.js.sha256)", - ], - data = [ - # ":bundle.umd.js" included as a dep as Bazel requires it for - # the "$(execpath :bundle.umd.js)" location expansion to work - ":bundle.umd.js", - # Also include ":bundle.umd" as a dep so that the module mappings - # from the ":bundle.umd" as propogated to ensure the linker - # handles these propogated mappings property - ":bundle.umd", - ], - tool = ":sha256", -) - -generated_file_test( - name = "test_umd_sha256", - src = ":golden.umd.js.sha256_", - generated = "bundle.umd.js.sha256", - # TODO: fix this test on Windows as sha256 differs - tags = ["fix-windows"], -)
diff --git a/packages/rollup/test/integration/accept.sh b/packages/rollup/test/integration/accept.sh deleted file mode 100755 index 528962f..0000000 --- a/packages/rollup/test/integration/accept.sh +++ /dev/null
@@ -1,13 +0,0 @@ -bazel run //packages/rollup/test/integration:test_amd.update -bazel run //packages/rollup/test/integration:test_cjs.update -bazel run //packages/rollup/test/integration:test_esm.update -bazel run //packages/rollup/test/integration:test_iife.update -bazel run //packages/rollup/test/integration:test_system.update -bazel run //packages/rollup/test/integration:test_umd.update -bazel run //packages/rollup/test/integration:test_amd_map_sha256.update -bazel run //packages/rollup/test/integration:test_cjs_map_sha256.update -bazel run //packages/rollup/test/integration:test_esm_map_sha256.update -bazel run //packages/rollup/test/integration:test_iife_map_sha256.update -bazel run //packages/rollup/test/integration:test_system_map_sha256.update -bazel run //packages/rollup/test/integration:test_umd_map_sha256.update -bazel run //packages/rollup/test/integration:test_umd_sha256.update
diff --git a/packages/rollup/test/integration/bar.js b/packages/rollup/test/integration/bar.js deleted file mode 100644 index 5195f60..0000000 --- a/packages/rollup/test/integration/bar.js +++ /dev/null
@@ -1 +0,0 @@ -export const name = 'Alice';
diff --git a/packages/rollup/test/integration/far/a/BUILD.bazel b/packages/rollup/test/integration/far/a/BUILD.bazel deleted file mode 100644 index ba1d69b..0000000 --- a/packages/rollup/test/integration/far/a/BUILD.bazel +++ /dev/null
@@ -1,14 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "js_library") -load("//packages/typescript:index.bzl", "ts_project") - -package(default_visibility = ["//packages/rollup:__subpackages__"]) - -ts_project( - srcs = glob(["*.ts"]), -) - -js_library( - name = "a", - package_name = "@far/a", - deps = [":tsconfig"], -)
diff --git a/packages/rollup/test/integration/far/a/b/c/BUILD.bazel b/packages/rollup/test/integration/far/a/b/c/BUILD.bazel deleted file mode 100644 index 1ff62b8..0000000 --- a/packages/rollup/test/integration/far/a/b/c/BUILD.bazel +++ /dev/null
@@ -1,14 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "js_library") -load("//packages/typescript:index.bzl", "ts_project") - -package(default_visibility = ["//packages/rollup:__subpackages__"]) - -ts_project( - srcs = glob(["*.ts"]), -) - -js_library( - name = "c", - package_name = "@far/a/b/c", - deps = [":tsconfig"], -)
diff --git a/packages/rollup/test/integration/far/a/b/c/index.ts b/packages/rollup/test/integration/far/a/b/c/index.ts deleted file mode 100644 index 9075058..0000000 --- a/packages/rollup/test/integration/far/a/b/c/index.ts +++ /dev/null
@@ -1 +0,0 @@ -export default `@far/a/b/c`;
diff --git a/packages/rollup/test/integration/far/a/b/c/tsconfig.json b/packages/rollup/test/integration/far/a/b/c/tsconfig.json deleted file mode 100644 index 11d727c..0000000 --- a/packages/rollup/test/integration/far/a/b/c/tsconfig.json +++ /dev/null
@@ -1,10 +0,0 @@ -{ - "compilerOptions": { - "lib": ["es2017", "dom"], - "strict": true, - "target": "es2015", - "module": "esnext", - "moduleResolution": "node", - "types": [] - } -}
diff --git a/packages/rollup/test/integration/far/a/index.ts b/packages/rollup/test/integration/far/a/index.ts deleted file mode 100644 index 4ff5142..0000000 --- a/packages/rollup/test/integration/far/a/index.ts +++ /dev/null
@@ -1 +0,0 @@ -export default `@far/a`;
diff --git a/packages/rollup/test/integration/far/a/tsconfig.json b/packages/rollup/test/integration/far/a/tsconfig.json deleted file mode 100644 index 09f8350..0000000 --- a/packages/rollup/test/integration/far/a/tsconfig.json +++ /dev/null
@@ -1,16 +0,0 @@ -{ - "compilerOptions": { - "lib": ["es2017", "dom"], - "strict": true, - "target": "es2015", - "module": "esnext", - "moduleResolution": "node", - "types": [] - }, - // For Windows, which is not sand-boxed, we need to limit - // the typescript files included so the "@far/a" compilation - // does not include typescript files from "@far/a/b/c" which - // is contained in a subdirectory. By default, typescript will - // include all typescript in the containing directory and subdirectories. - "include": ["*.ts"] -}
diff --git a/packages/rollup/test/integration/file.js b/packages/rollup/test/integration/file.js deleted file mode 100644 index e7d978a..0000000 --- a/packages/rollup/test/integration/file.js +++ /dev/null
@@ -1,3 +0,0 @@ -/** - * @fileoverview Description of this file. - */
diff --git a/packages/rollup/test/integration/foo.js b/packages/rollup/test/integration/foo.js deleted file mode 100644 index 5a3febd..0000000 --- a/packages/rollup/test/integration/foo.js +++ /dev/null
@@ -1,37 +0,0 @@ -import far_a from '@far/a'; -import far_a_b_c from '@far/a/b/c'; -import {foo} from '@foo/lib'; -import {foo as foo_a} from '@foo/lib/a'; -import {foo as foo_a_a_a} from '@foo/lib/a/a/a'; -import {fum} from 'fumlib'; -import hello from 'hello'; -import {thing} from 'some_global_var'; - -import {name} from './bar'; -import {json_key} from './some.json'; - -console.log( - `${hello}, ${name} in ${fum} ${foo} ${foo_a} ${foo_a_a_a} ${far_a} ${far_a_b_c} ${json_key}`); - -// Tests for @PURE annotations -/*@__PURE__*/ -console.log('side-effect'); - -class Impure { - constructor() { - console.log('side-effect') - } -} - -/*@__PURE__*/ new Impure(); - -// Test for sequences = false -export class A { - a() { - return document.a; - } -} -function inline_me() { - return 'abc'; -} -console.error(new A().a(), inline_me(), thing);
diff --git a/packages/rollup/test/integration/foo/BUILD.bazel b/packages/rollup/test/integration/foo/BUILD.bazel deleted file mode 100644 index 4fd5edc..0000000 --- a/packages/rollup/test/integration/foo/BUILD.bazel +++ /dev/null
@@ -1,32 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "js_library") -load("//packages/typescript:index.bzl", "ts_project") -load("//third_party/github.com/bazelbuild/bazel-skylib:rules/copy_file.bzl", "copy_file") - -package(default_visibility = ["//packages/rollup:__subpackages__"]) - -copy_file( - name = "copy_user", - src = ":user.mjs", - out = ":user.js", -) - -ts_project( - name = "foo_tslib", - srcs = [ - "index.ts", - "user.d.ts", - ], - tsconfig = ":tsconfig.json", - deps = ["@npm//date-fns"], -) - -js_library( - name = "foo_lib", - package_name = "@foo/lib", - srcs = [ - ":user.js", - ], - deps = [ - ":foo_tslib", - ], -)
diff --git a/packages/rollup/test/integration/foo/index.ts b/packages/rollup/test/integration/foo/index.ts deleted file mode 100644 index 216ac12..0000000 --- a/packages/rollup/test/integration/foo/index.ts +++ /dev/null
@@ -1,6 +0,0 @@ -import {format} from 'date-fns'; - -import {user} from './user'; - -const date: string = format(new Date(2019, 4, 7), 'MMMM D, YYYY'); -export const foo = `Sunnyvale ${user} ${date}`;
diff --git a/packages/rollup/test/integration/foo/tsconfig.json b/packages/rollup/test/integration/foo/tsconfig.json deleted file mode 100644 index 11d727c..0000000 --- a/packages/rollup/test/integration/foo/tsconfig.json +++ /dev/null
@@ -1,10 +0,0 @@ -{ - "compilerOptions": { - "lib": ["es2017", "dom"], - "strict": true, - "target": "es2015", - "module": "esnext", - "moduleResolution": "node", - "types": [] - } -}
diff --git a/packages/rollup/test/integration/foo/user.d.ts b/packages/rollup/test/integration/foo/user.d.ts deleted file mode 100644 index 8ca94d1..0000000 --- a/packages/rollup/test/integration/foo/user.d.ts +++ /dev/null
@@ -1 +0,0 @@ -export declare const user = 'user'; \ No newline at end of file
diff --git a/packages/rollup/test/integration/foo/user.mjs b/packages/rollup/test/integration/foo/user.mjs deleted file mode 100644 index dc3c952..0000000 --- a/packages/rollup/test/integration/foo/user.mjs +++ /dev/null
@@ -1 +0,0 @@ -export const user = "user"; \ No newline at end of file
diff --git a/packages/rollup/test/integration/foo_a/BUILD.bazel b/packages/rollup/test/integration/foo_a/BUILD.bazel deleted file mode 100644 index eddbee1..0000000 --- a/packages/rollup/test/integration/foo_a/BUILD.bazel +++ /dev/null
@@ -1,15 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "js_library") -load("//packages/typescript:index.bzl", "ts_project") - -package(default_visibility = ["//packages/rollup:__subpackages__"]) - -ts_project( - srcs = ["index.ts"], - deps = ["@npm//date-fns"], -) - -js_library( - name = "foo_lib_a", - package_name = "@foo/lib/a", - srcs = [":index.js"], -)
diff --git a/packages/rollup/test/integration/foo_a/index.ts b/packages/rollup/test/integration/foo_a/index.ts deleted file mode 100644 index fffb222..0000000 --- a/packages/rollup/test/integration/foo_a/index.ts +++ /dev/null
@@ -1,4 +0,0 @@ -import {format} from 'date-fns'; - -const date: string = format(new Date(2019, 4, 7), 'MMMM D, YYYY'); -export const foo = `@foo/lib/a ${date}`;
diff --git a/packages/rollup/test/integration/foo_a/tsconfig.json b/packages/rollup/test/integration/foo_a/tsconfig.json deleted file mode 100644 index 11d727c..0000000 --- a/packages/rollup/test/integration/foo_a/tsconfig.json +++ /dev/null
@@ -1,10 +0,0 @@ -{ - "compilerOptions": { - "lib": ["es2017", "dom"], - "strict": true, - "target": "es2015", - "module": "esnext", - "moduleResolution": "node", - "types": [] - } -}
diff --git a/packages/rollup/test/integration/foo_aaa/BUILD.bazel b/packages/rollup/test/integration/foo_aaa/BUILD.bazel deleted file mode 100644 index 1989c2a..0000000 --- a/packages/rollup/test/integration/foo_aaa/BUILD.bazel +++ /dev/null
@@ -1,15 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "js_library") -load("//packages/typescript:index.bzl", "ts_project") - -package(default_visibility = ["//packages/rollup:__subpackages__"]) - -ts_project( - srcs = ["index.ts"], - deps = ["@npm//date-fns"], -) - -js_library( - name = "foo_lib_a_a_a", - package_name = "@foo/lib/a/a/a", - srcs = [":index.js"], -)
diff --git a/packages/rollup/test/integration/foo_aaa/index.ts b/packages/rollup/test/integration/foo_aaa/index.ts deleted file mode 100644 index 42bb649..0000000 --- a/packages/rollup/test/integration/foo_aaa/index.ts +++ /dev/null
@@ -1,4 +0,0 @@ -import {format} from 'date-fns'; - -const date: string = format(new Date(2019, 4, 7), 'MMMM D, YYYY'); -export const foo = `@foo/lib/a/a/a ${date}`;
diff --git a/packages/rollup/test/integration/foo_aaa/tsconfig.json b/packages/rollup/test/integration/foo_aaa/tsconfig.json deleted file mode 100644 index 11d727c..0000000 --- a/packages/rollup/test/integration/foo_aaa/tsconfig.json +++ /dev/null
@@ -1,10 +0,0 @@ -{ - "compilerOptions": { - "lib": ["es2017", "dom"], - "strict": true, - "target": "es2015", - "module": "esnext", - "moduleResolution": "node", - "types": [] - } -}
diff --git a/packages/rollup/test/integration/fum/BUILD.bazel b/packages/rollup/test/integration/fum/BUILD.bazel deleted file mode 100644 index d37f63d..0000000 --- a/packages/rollup/test/integration/fum/BUILD.bazel +++ /dev/null
@@ -1,9 +0,0 @@ -load("//:index.bzl", "js_library") - -package(default_visibility = ["//packages/rollup:__subpackages__"]) - -js_library( - name = "fumlib", - package_name = "fumlib", - srcs = ["index.js"], -)
diff --git a/packages/rollup/test/integration/fum/index.js b/packages/rollup/test/integration/fum/index.js deleted file mode 100644 index 82c2219..0000000 --- a/packages/rollup/test/integration/fum/index.js +++ /dev/null
@@ -1 +0,0 @@ -export const fum = 'Wonderland';
diff --git a/packages/rollup/test/integration/golden.amd.js.map.sha256_ b/packages/rollup/test/integration/golden.amd.js.map.sha256_ deleted file mode 100644 index eabab1f..0000000 --- a/packages/rollup/test/integration/golden.amd.js.map.sha256_ +++ /dev/null
@@ -1 +0,0 @@ -67c2d1c41362085ed0cdf54cf039cbe8f8e70dbbfad49b2e26d5ca33bf6af406 \ No newline at end of file
diff --git a/packages/rollup/test/integration/golden.amd.js_ b/packages/rollup/test/integration/golden.amd.js_ deleted file mode 100644 index 1325231..0000000 --- a/packages/rollup/test/integration/golden.amd.js_ +++ /dev/null
@@ -1,5682 +0,0 @@ -/** - * @license A dummy license banner that goes at the top of the file. - * This is version <unknown> - */ - -define(['exports', 'some_global_var'], function (exports, some_global_var) { 'use strict'; - - var far_a = `@far/a`; - - var far_a_b_c = `@far/a/b/c`; - - var MILLISECONDS_IN_MINUTE$6 = 60000; - - /** - * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. - * They usually appear for dates that denote time before the timezones were introduced - * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 - * and GMT+01:00:00 after that date) - * - * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above, - * which would lead to incorrect calculations. - * - * This function returns the timezone offset in milliseconds that takes seconds in account. - */ - var getTimezoneOffsetInMilliseconds = function getTimezoneOffsetInMilliseconds (dirtyDate) { - var date = new Date(dirtyDate.getTime()); - var baseTimezoneOffset = date.getTimezoneOffset(); - date.setSeconds(0, 0); - var millisecondsPartOfTimezoneOffset = date.getTime() % MILLISECONDS_IN_MINUTE$6; - - return baseTimezoneOffset * MILLISECONDS_IN_MINUTE$6 + millisecondsPartOfTimezoneOffset - }; - - /** - * @category Common Helpers - * @summary Is the given argument an instance of Date? - * - * @description - * Is the given argument an instance of Date? - * - * @param {*} argument - the argument to check - * @returns {Boolean} the given argument is an instance of Date - * - * @example - * // Is 'mayonnaise' a Date? - * var result = isDate('mayonnaise') - * //=> false - */ - function isDate (argument) { - return argument instanceof Date - } - - var is_date = isDate; - - var MILLISECONDS_IN_HOUR$2 = 3600000; - var MILLISECONDS_IN_MINUTE$5 = 60000; - var DEFAULT_ADDITIONAL_DIGITS = 2; - - var parseTokenDateTimeDelimeter = /[T ]/; - var parseTokenPlainTime = /:/; - - // year tokens - var parseTokenYY = /^(\d{2})$/; - var parseTokensYYY = [ - /^([+-]\d{2})$/, // 0 additional digits - /^([+-]\d{3})$/, // 1 additional digit - /^([+-]\d{4})$/ // 2 additional digits - ]; - - var parseTokenYYYY = /^(\d{4})/; - var parseTokensYYYYY = [ - /^([+-]\d{4})/, // 0 additional digits - /^([+-]\d{5})/, // 1 additional digit - /^([+-]\d{6})/ // 2 additional digits - ]; - - // date tokens - var parseTokenMM = /^-(\d{2})$/; - var parseTokenDDD = /^-?(\d{3})$/; - var parseTokenMMDD = /^-?(\d{2})-?(\d{2})$/; - var parseTokenWww = /^-?W(\d{2})$/; - var parseTokenWwwD = /^-?W(\d{2})-?(\d{1})$/; - - // time tokens - var parseTokenHH = /^(\d{2}([.,]\d*)?)$/; - var parseTokenHHMM = /^(\d{2}):?(\d{2}([.,]\d*)?)$/; - var parseTokenHHMMSS = /^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/; - - // timezone tokens - var parseTokenTimezone = /([Z+-].*)$/; - var parseTokenTimezoneZ = /^(Z)$/; - var parseTokenTimezoneHH = /^([+-])(\d{2})$/; - var parseTokenTimezoneHHMM = /^([+-])(\d{2}):?(\d{2})$/; - - /** - * @category Common Helpers - * @summary Convert the given argument to an instance of Date. - * - * @description - * Convert the given argument to an instance of Date. - * - * If the argument is an instance of Date, the function returns its clone. - * - * If the argument is a number, it is treated as a timestamp. - * - * If an argument is a string, the function tries to parse it. - * Function accepts complete ISO 8601 formats as well as partial implementations. - * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 - * - * If all above fails, the function passes the given argument to Date constructor. - * - * @param {Date|String|Number} argument - the value to convert - * @param {Object} [options] - the object with options - * @param {0 | 1 | 2} [options.additionalDigits=2] - the additional number of digits in the extended year format - * @returns {Date} the parsed date in the local time zone - * - * @example - * // Convert string '2014-02-11T11:30:30' to date: - * var result = parse('2014-02-11T11:30:30') - * //=> Tue Feb 11 2014 11:30:30 - * - * @example - * // Parse string '+02014101', - * // if the additional number of digits in the extended year format is 1: - * var result = parse('+02014101', {additionalDigits: 1}) - * //=> Fri Apr 11 2014 00:00:00 - */ - function parse (argument, dirtyOptions) { - if (is_date(argument)) { - // Prevent the date to lose the milliseconds when passed to new Date() in IE10 - return new Date(argument.getTime()) - } else if (typeof argument !== 'string') { - return new Date(argument) - } - - var options = dirtyOptions || {}; - var additionalDigits = options.additionalDigits; - if (additionalDigits == null) { - additionalDigits = DEFAULT_ADDITIONAL_DIGITS; - } else { - additionalDigits = Number(additionalDigits); - } - - var dateStrings = splitDateString(argument); - - var parseYearResult = parseYear(dateStrings.date, additionalDigits); - var year = parseYearResult.year; - var restDateString = parseYearResult.restDateString; - - var date = parseDate(restDateString, year); - - if (date) { - var timestamp = date.getTime(); - var time = 0; - var offset; - - if (dateStrings.time) { - time = parseTime(dateStrings.time); - } - - if (dateStrings.timezone) { - offset = parseTimezone(dateStrings.timezone) * MILLISECONDS_IN_MINUTE$5; - } else { - var fullTime = timestamp + time; - var fullTimeDate = new Date(fullTime); - - offset = getTimezoneOffsetInMilliseconds(fullTimeDate); - - // Adjust time when it's coming from DST - var fullTimeDateNextDay = new Date(fullTime); - fullTimeDateNextDay.setDate(fullTimeDate.getDate() + 1); - var offsetDiff = - getTimezoneOffsetInMilliseconds(fullTimeDateNextDay) - - getTimezoneOffsetInMilliseconds(fullTimeDate); - if (offsetDiff > 0) { - offset += offsetDiff; - } - } - - return new Date(timestamp + time + offset) - } else { - return new Date(argument) - } - } - - function splitDateString (dateString) { - var dateStrings = {}; - var array = dateString.split(parseTokenDateTimeDelimeter); - var timeString; - - if (parseTokenPlainTime.test(array[0])) { - dateStrings.date = null; - timeString = array[0]; - } else { - dateStrings.date = array[0]; - timeString = array[1]; - } - - if (timeString) { - var token = parseTokenTimezone.exec(timeString); - if (token) { - dateStrings.time = timeString.replace(token[1], ''); - dateStrings.timezone = token[1]; - } else { - dateStrings.time = timeString; - } - } - - return dateStrings - } - - function parseYear (dateString, additionalDigits) { - var parseTokenYYY = parseTokensYYY[additionalDigits]; - var parseTokenYYYYY = parseTokensYYYYY[additionalDigits]; - - var token; - - // YYYY or ±YYYYY - token = parseTokenYYYY.exec(dateString) || parseTokenYYYYY.exec(dateString); - if (token) { - var yearString = token[1]; - return { - year: parseInt(yearString, 10), - restDateString: dateString.slice(yearString.length) - } - } - - // YY or ±YYY - token = parseTokenYY.exec(dateString) || parseTokenYYY.exec(dateString); - if (token) { - var centuryString = token[1]; - return { - year: parseInt(centuryString, 10) * 100, - restDateString: dateString.slice(centuryString.length) - } - } - - // Invalid ISO-formatted year - return { - year: null - } - } - - function parseDate (dateString, year) { - // Invalid ISO-formatted year - if (year === null) { - return null - } - - var token; - var date; - var month; - var week; - - // YYYY - if (dateString.length === 0) { - date = new Date(0); - date.setUTCFullYear(year); - return date - } - - // YYYY-MM - token = parseTokenMM.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - date.setUTCFullYear(year, month); - return date - } - - // YYYY-DDD or YYYYDDD - token = parseTokenDDD.exec(dateString); - if (token) { - date = new Date(0); - var dayOfYear = parseInt(token[1], 10); - date.setUTCFullYear(year, 0, dayOfYear); - return date - } - - // YYYY-MM-DD or YYYYMMDD - token = parseTokenMMDD.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - var day = parseInt(token[2], 10); - date.setUTCFullYear(year, month, day); - return date - } - - // YYYY-Www or YYYYWww - token = parseTokenWww.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - return dayOfISOYear(year, week) - } - - // YYYY-Www-D or YYYYWwwD - token = parseTokenWwwD.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - var dayOfWeek = parseInt(token[2], 10) - 1; - return dayOfISOYear(year, week, dayOfWeek) - } - - // Invalid ISO-formatted date - return null - } - - function parseTime (timeString) { - var token; - var hours; - var minutes; - - // hh - token = parseTokenHH.exec(timeString); - if (token) { - hours = parseFloat(token[1].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 - } - - // hh:mm or hhmm - token = parseTokenHHMM.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseFloat(token[2].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 - } - - // hh:mm:ss or hhmmss - token = parseTokenHHMMSS.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseInt(token[2], 10); - var seconds = parseFloat(token[3].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 + - seconds * 1000 - } - - // Invalid ISO-formatted time - return null - } - - function parseTimezone (timezoneString) { - var token; - var absoluteOffset; - - // Z - token = parseTokenTimezoneZ.exec(timezoneString); - if (token) { - return 0 - } - - // ±hh - token = parseTokenTimezoneHH.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60; - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - // ±hh:mm or ±hhmm - token = parseTokenTimezoneHHMM.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60 + parseInt(token[3], 10); - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - return 0 - } - - function dayOfISOYear (isoYear, week, day) { - week = week || 0; - day = day || 0; - var date = new Date(0); - date.setUTCFullYear(isoYear, 0, 4); - var fourthOfJanuaryDay = date.getUTCDay() || 7; - var diff = week * 7 + day + 1 - fourthOfJanuaryDay; - date.setUTCDate(date.getUTCDate() + diff); - return date - } - - var parse_1 = parse; - - /** - * @category Day Helpers - * @summary Add the specified number of days to the given date. - * - * @description - * Add the specified number of days to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be added - * @returns {Date} the new date with the days added - * - * @example - * // Add 10 days to 1 September 2014: - * var result = addDays(new Date(2014, 8, 1), 10) - * //=> Thu Sep 11 2014 00:00:00 - */ - function addDays (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - date.setDate(date.getDate() + amount); - return date - } - - var add_days = addDays; - - /** - * @category Millisecond Helpers - * @summary Add the specified number of milliseconds to the given date. - * - * @description - * Add the specified number of milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be added - * @returns {Date} the new date with the milliseconds added - * - * @example - * // Add 750 milliseconds to 10 July 2014 12:45:30.000: - * var result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:30.750 - */ - function addMilliseconds (dirtyDate, dirtyAmount) { - var timestamp = parse_1(dirtyDate).getTime(); - var amount = Number(dirtyAmount); - return new Date(timestamp + amount) - } - - var add_milliseconds = addMilliseconds; - - var MILLISECONDS_IN_HOUR$1 = 3600000; - - /** - * @category Hour Helpers - * @summary Add the specified number of hours to the given date. - * - * @description - * Add the specified number of hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be added - * @returns {Date} the new date with the hours added - * - * @example - * // Add 2 hours to 10 July 2014 23:00:00: - * var result = addHours(new Date(2014, 6, 10, 23, 0), 2) - * //=> Fri Jul 11 2014 01:00:00 - */ - function addHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR$1) - } - - var add_hours = addHours; - - /** - * @category Week Helpers - * @summary Return the start of a week for the given date. - * - * @description - * Return the start of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the start of a week - * - * @example - * // The start of a week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - - date.setDate(date.getDate() - diff); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_week = startOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the start of an ISO week for the given date. - * - * @description - * Return the start of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO week - * - * @example - * // The start of an ISO week for 2 September 2014 11:55:00: - * var result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfISOWeek (dirtyDate) { - return start_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var start_of_iso_week = startOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the ISO week-numbering year of the given date. - * - * @description - * Get the ISO week-numbering year of the given date, - * which always starts 3 days before the year's first Thursday. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week-numbering year - * - * @example - * // Which ISO-week numbering year is 2 January 2005? - * var result = getISOYear(new Date(2005, 0, 2)) - * //=> 2004 - */ - function getISOYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var startOfNextYear = start_of_iso_week(fourthOfJanuaryOfNextYear); - - var fourthOfJanuaryOfThisYear = new Date(0); - fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); - fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); - var startOfThisYear = start_of_iso_week(fourthOfJanuaryOfThisYear); - - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1 - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year - } else { - return year - 1 - } - } - - var get_iso_year = getISOYear; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the start of an ISO week-numbering year for the given date. - * - * @description - * Return the start of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO year - * - * @example - * // The start of an ISO week-numbering year for 2 July 2005: - * var result = startOfISOYear(new Date(2005, 6, 2)) - * //=> Mon Jan 03 2005 00:00:00 - */ - function startOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - return date - } - - var start_of_iso_year = startOfISOYear; - - /** - * @category Day Helpers - * @summary Return the start of a day for the given date. - * - * @description - * Return the start of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a day - * - * @example - * // The start of a day for 2 September 2014 11:55:00: - * var result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 00:00:00 - */ - function startOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_day = startOfDay; - - var MILLISECONDS_IN_MINUTE$4 = 60000; - var MILLISECONDS_IN_DAY$1 = 86400000; - - /** - * @category Day Helpers - * @summary Get the number of calendar days between the given dates. - * - * @description - * Get the number of calendar days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar days - * - * @example - * // How many calendar days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInCalendarDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 366 - */ - function differenceInCalendarDays (dirtyDateLeft, dirtyDateRight) { - var startOfDayLeft = start_of_day(dirtyDateLeft); - var startOfDayRight = start_of_day(dirtyDateRight); - - var timestampLeft = startOfDayLeft.getTime() - - startOfDayLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - var timestampRight = startOfDayRight.getTime() - - startOfDayRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a day is not constant - // (e.g. it's different in the day of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY$1) - } - - var difference_in_calendar_days = differenceInCalendarDays; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Set the ISO week-numbering year to the given date. - * - * @description - * Set the ISO week-numbering year to the given date, - * saving the week number and the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoYear - the ISO week-numbering year of the new date - * @returns {Date} the new date with the ISO week-numbering year setted - * - * @example - * // Set ISO week-numbering year 2007 to 29 December 2008: - * var result = setISOYear(new Date(2008, 11, 29), 2007) - * //=> Mon Jan 01 2007 00:00:00 - */ - function setISOYear (dirtyDate, dirtyISOYear) { - var date = parse_1(dirtyDate); - var isoYear = Number(dirtyISOYear); - var diff = difference_in_calendar_days(date, start_of_iso_year(date)); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(isoYear, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - date = start_of_iso_year(fourthOfJanuary); - date.setDate(date.getDate() + diff); - return date - } - - var set_iso_year = setISOYear; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Add the specified number of ISO week-numbering years to the given date. - * - * @description - * Add the specified number of ISO week-numbering years to the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be added - * @returns {Date} the new date with the ISO week-numbering years added - * - * @example - * // Add 5 ISO week-numbering years to 2 July 2010: - * var result = addISOYears(new Date(2010, 6, 2), 5) - * //=> Fri Jun 26 2015 00:00:00 - */ - function addISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return set_iso_year(dirtyDate, get_iso_year(dirtyDate) + amount) - } - - var add_iso_years = addISOYears; - - var MILLISECONDS_IN_MINUTE$3 = 60000; - - /** - * @category Minute Helpers - * @summary Add the specified number of minutes to the given date. - * - * @description - * Add the specified number of minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be added - * @returns {Date} the new date with the minutes added - * - * @example - * // Add 30 minutes to 10 July 2014 12:00:00: - * var result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 12:30:00 - */ - function addMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE$3) - } - - var add_minutes = addMinutes; - - /** - * @category Month Helpers - * @summary Get the number of days in a month of the given date. - * - * @description - * Get the number of days in a month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a month - * - * @example - * // How many days are in February 2000? - * var result = getDaysInMonth(new Date(2000, 1)) - * //=> 29 - */ - function getDaysInMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - var monthIndex = date.getMonth(); - var lastDayOfMonth = new Date(0); - lastDayOfMonth.setFullYear(year, monthIndex + 1, 0); - lastDayOfMonth.setHours(0, 0, 0, 0); - return lastDayOfMonth.getDate() - } - - var get_days_in_month = getDaysInMonth; - - /** - * @category Month Helpers - * @summary Add the specified number of months to the given date. - * - * @description - * Add the specified number of months to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be added - * @returns {Date} the new date with the months added - * - * @example - * // Add 5 months to 1 September 2014: - * var result = addMonths(new Date(2014, 8, 1), 5) - * //=> Sun Feb 01 2015 00:00:00 - */ - function addMonths (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - var desiredMonth = date.getMonth() + amount; - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(date.getFullYear(), desiredMonth, 1); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(desiredMonth, Math.min(daysInMonth, date.getDate())); - return date - } - - var add_months = addMonths; - - /** - * @category Quarter Helpers - * @summary Add the specified number of year quarters to the given date. - * - * @description - * Add the specified number of year quarters to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be added - * @returns {Date} the new date with the quarters added - * - * @example - * // Add 1 quarter to 1 September 2014: - * var result = addQuarters(new Date(2014, 8, 1), 1) - * //=> Mon Dec 01 2014 00:00:00 - */ - function addQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var months = amount * 3; - return add_months(dirtyDate, months) - } - - var add_quarters = addQuarters; - - /** - * @category Second Helpers - * @summary Add the specified number of seconds to the given date. - * - * @description - * Add the specified number of seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be added - * @returns {Date} the new date with the seconds added - * - * @example - * // Add 30 seconds to 10 July 2014 12:45:00: - * var result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:45:30 - */ - function addSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * 1000) - } - - var add_seconds = addSeconds; - - /** - * @category Week Helpers - * @summary Add the specified number of weeks to the given date. - * - * @description - * Add the specified number of week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be added - * @returns {Date} the new date with the weeks added - * - * @example - * // Add 4 weeks to 1 September 2014: - * var result = addWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Sep 29 2014 00:00:00 - */ - function addWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var days = amount * 7; - return add_days(dirtyDate, days) - } - - var add_weeks = addWeeks; - - /** - * @category Year Helpers - * @summary Add the specified number of years to the given date. - * - * @description - * Add the specified number of years to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be added - * @returns {Date} the new date with the years added - * - * @example - * // Add 5 years to 1 September 2014: - * var result = addYears(new Date(2014, 8, 1), 5) - * //=> Sun Sep 01 2019 00:00:00 - */ - function addYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, amount * 12) - } - - var add_years = addYears; - - /** - * @category Range Helpers - * @summary Is the given date range overlapping with another date range? - * - * @description - * Is the given date range overlapping with another date range? - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Boolean} whether the date ranges are overlapping - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> true - * - * @example - * // For non-overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> false - */ - function areRangesOverlapping (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return initialStartTime < comparedEndTime && comparedStartTime < initialEndTime - } - - var are_ranges_overlapping = areRangesOverlapping; - - /** - * @category Common Helpers - * @summary Return an index of the closest date from the array comparing to the given date. - * - * @description - * Return an index of the closest date from the array comparing to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Number} an index of the date closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015? - * var dateToCompare = new Date(2015, 8, 6) - * var datesArray = [ - * new Date(2015, 0, 1), - * new Date(2016, 0, 1), - * new Date(2017, 0, 1) - * ] - * var result = closestIndexTo(dateToCompare, datesArray) - * //=> 1 - */ - function closestIndexTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate, index) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = index; - minDistance = distance; - } - }); - - return result - } - - var closest_index_to = closestIndexTo; - - /** - * @category Common Helpers - * @summary Return a date from the array closest to the given date. - * - * @description - * Return a date from the array closest to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Date} the date from the array closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030? - * var dateToCompare = new Date(2015, 8, 6) - * var result = closestTo(dateToCompare, [ - * new Date(2000, 0, 1), - * new Date(2030, 0, 1) - * ]) - * //=> Tue Jan 01 2030 00:00:00 - */ - function closestTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = currentDate; - minDistance = distance; - } - }); - - return result - } - - var closest_to = closestTo; - - /** - * @category Common Helpers - * @summary Compare the two dates and return -1, 0 or 1. - * - * @description - * Compare the two dates and return 1 if the first date is after the second, - * -1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989: - * var result = compareAsc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> -1 - * - * @example - * // Sort the array of dates: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareAsc) - * //=> [ - * // Wed Feb 11 1987 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Sun Jul 02 1995 00:00:00 - * // ] - */ - function compareAsc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft < timeRight) { - return -1 - } else if (timeLeft > timeRight) { - return 1 - } else { - return 0 - } - } - - var compare_asc = compareAsc; - - /** - * @category Common Helpers - * @summary Compare the two dates reverse chronologically and return -1, 0 or 1. - * - * @description - * Compare the two dates and return -1 if the first date is after the second, - * 1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989 reverse chronologically: - * var result = compareDesc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> 1 - * - * @example - * // Sort the array of dates in reverse chronological order: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareDesc) - * //=> [ - * // Sun Jul 02 1995 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Wed Feb 11 1987 00:00:00 - * // ] - */ - function compareDesc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft > timeRight) { - return -1 - } else if (timeLeft < timeRight) { - return 1 - } else { - return 0 - } - } - - var compare_desc = compareDesc; - - var MILLISECONDS_IN_MINUTE$2 = 60000; - var MILLISECONDS_IN_WEEK$3 = 604800000; - - /** - * @category ISO Week Helpers - * @summary Get the number of calendar ISO weeks between the given dates. - * - * @description - * Get the number of calendar ISO weeks between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO weeks - * - * @example - * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014? - * var result = differenceInCalendarISOWeeks( - * new Date(2014, 6, 21), - * new Date(2014, 6, 6) - * ) - * //=> 3 - */ - function differenceInCalendarISOWeeks (dirtyDateLeft, dirtyDateRight) { - var startOfISOWeekLeft = start_of_iso_week(dirtyDateLeft); - var startOfISOWeekRight = start_of_iso_week(dirtyDateRight); - - var timestampLeft = startOfISOWeekLeft.getTime() - - startOfISOWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - var timestampRight = startOfISOWeekRight.getTime() - - startOfISOWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$3) - } - - var difference_in_calendar_iso_weeks = differenceInCalendarISOWeeks; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of calendar ISO week-numbering years between the given dates. - * - * @description - * Get the number of calendar ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO week-numbering years - * - * @example - * // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012? - * var result = differenceInCalendarISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 2 - */ - function differenceInCalendarISOYears (dirtyDateLeft, dirtyDateRight) { - return get_iso_year(dirtyDateLeft) - get_iso_year(dirtyDateRight) - } - - var difference_in_calendar_iso_years = differenceInCalendarISOYears; - - /** - * @category Month Helpers - * @summary Get the number of calendar months between the given dates. - * - * @description - * Get the number of calendar months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar months - * - * @example - * // How many calendar months are between 31 January 2014 and 1 September 2014? - * var result = differenceInCalendarMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 8 - */ - function differenceInCalendarMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); - - return yearDiff * 12 + monthDiff - } - - var difference_in_calendar_months = differenceInCalendarMonths; - - /** - * @category Quarter Helpers - * @summary Get the year quarter of the given date. - * - * @description - * Get the year quarter of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the quarter - * - * @example - * // Which quarter is 2 July 2014? - * var result = getQuarter(new Date(2014, 6, 2)) - * //=> 3 - */ - function getQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var quarter = Math.floor(date.getMonth() / 3) + 1; - return quarter - } - - var get_quarter = getQuarter; - - /** - * @category Quarter Helpers - * @summary Get the number of calendar quarters between the given dates. - * - * @description - * Get the number of calendar quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar quarters - * - * @example - * // How many calendar quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInCalendarQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 3 - */ - function differenceInCalendarQuarters (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var quarterDiff = get_quarter(dateLeft) - get_quarter(dateRight); - - return yearDiff * 4 + quarterDiff - } - - var difference_in_calendar_quarters = differenceInCalendarQuarters; - - var MILLISECONDS_IN_MINUTE$1 = 60000; - var MILLISECONDS_IN_WEEK$2 = 604800000; - - /** - * @category Week Helpers - * @summary Get the number of calendar weeks between the given dates. - * - * @description - * Get the number of calendar weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Number} the number of calendar weeks - * - * @example - * // How many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 3 - * - * @example - * // If the week starts on Monday, - * // how many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5), - * {weekStartsOn: 1} - * ) - * //=> 2 - */ - function differenceInCalendarWeeks (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var startOfWeekLeft = start_of_week(dirtyDateLeft, dirtyOptions); - var startOfWeekRight = start_of_week(dirtyDateRight, dirtyOptions); - - var timestampLeft = startOfWeekLeft.getTime() - - startOfWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - var timestampRight = startOfWeekRight.getTime() - - startOfWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$2) - } - - var difference_in_calendar_weeks = differenceInCalendarWeeks; - - /** - * @category Year Helpers - * @summary Get the number of calendar years between the given dates. - * - * @description - * Get the number of calendar years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar years - * - * @example - * // How many calendar years are between 31 December 2013 and 11 February 2015? - * var result = differenceInCalendarYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ - function differenceInCalendarYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - return dateLeft.getFullYear() - dateRight.getFullYear() - } - - var difference_in_calendar_years = differenceInCalendarYears; - - /** - * @category Day Helpers - * @summary Get the number of full days between the given dates. - * - * @description - * Get the number of full days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full days - * - * @example - * // How many full days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 365 - */ - function differenceInDays (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_days(dateLeft, dateRight)); - dateLeft.setDate(dateLeft.getDate() - sign * difference); - - // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full - // If so, result must be decreased by 1 in absolute value - var isLastDayNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastDayNotFull) - } - - var difference_in_days = differenceInDays; - - /** - * @category Millisecond Helpers - * @summary Get the number of milliseconds between the given dates. - * - * @description - * Get the number of milliseconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of milliseconds - * - * @example - * // How many milliseconds are between - * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700? - * var result = differenceInMilliseconds( - * new Date(2014, 6, 2, 12, 30, 21, 700), - * new Date(2014, 6, 2, 12, 30, 20, 600) - * ) - * //=> 1100 - */ - function differenceInMilliseconds (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getTime() - dateRight.getTime() - } - - var difference_in_milliseconds = differenceInMilliseconds; - - var MILLISECONDS_IN_HOUR = 3600000; - - /** - * @category Hour Helpers - * @summary Get the number of hours between the given dates. - * - * @description - * Get the number of hours between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of hours - * - * @example - * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00? - * var result = differenceInHours( - * new Date(2014, 6, 2, 19, 0), - * new Date(2014, 6, 2, 6, 50) - * ) - * //=> 12 - */ - function differenceInHours (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_hours = differenceInHours; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Subtract the specified number of ISO week-numbering years from the given date. - * - * @description - * Subtract the specified number of ISO week-numbering years from the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be subtracted - * @returns {Date} the new date with the ISO week-numbering years subtracted - * - * @example - * // Subtract 5 ISO week-numbering years from 1 September 2014: - * var result = subISOYears(new Date(2014, 8, 1), 5) - * //=> Mon Aug 31 2009 00:00:00 - */ - function subISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_iso_years(dirtyDate, -amount) - } - - var sub_iso_years = subISOYears; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of full ISO week-numbering years between the given dates. - * - * @description - * Get the number of full ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full ISO week-numbering years - * - * @example - * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012? - * var result = differenceInISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 1 - */ - function differenceInISOYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_iso_years(dateLeft, dateRight)); - dateLeft = sub_iso_years(dateLeft, sign * difference); - - // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1 - // if last calendar ISO year is not full - // If so, result must be decreased by 1 in absolute value - var isLastISOYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastISOYearNotFull) - } - - var difference_in_iso_years = differenceInISOYears; - - var MILLISECONDS_IN_MINUTE = 60000; - - /** - * @category Minute Helpers - * @summary Get the number of minutes between the given dates. - * - * @description - * Get the number of minutes between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of minutes - * - * @example - * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00? - * var result = differenceInMinutes( - * new Date(2014, 6, 2, 12, 20, 0), - * new Date(2014, 6, 2, 12, 7, 59) - * ) - * //=> 12 - */ - function differenceInMinutes (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_minutes = differenceInMinutes; - - /** - * @category Month Helpers - * @summary Get the number of full months between the given dates. - * - * @description - * Get the number of full months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full months - * - * @example - * // How many full months are between 31 January 2014 and 1 September 2014? - * var result = differenceInMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 7 - */ - function differenceInMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_months(dateLeft, dateRight)); - dateLeft.setMonth(dateLeft.getMonth() - sign * difference); - - // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full - // If so, result must be decreased by 1 in absolute value - var isLastMonthNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastMonthNotFull) - } - - var difference_in_months = differenceInMonths; - - /** - * @category Quarter Helpers - * @summary Get the number of full quarters between the given dates. - * - * @description - * Get the number of full quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full quarters - * - * @example - * // How many full quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ - function differenceInQuarters (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_months(dirtyDateLeft, dirtyDateRight) / 3; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_quarters = differenceInQuarters; - - /** - * @category Second Helpers - * @summary Get the number of seconds between the given dates. - * - * @description - * Get the number of seconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of seconds - * - * @example - * // How many seconds are between - * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000? - * var result = differenceInSeconds( - * new Date(2014, 6, 2, 12, 30, 20, 0), - * new Date(2014, 6, 2, 12, 30, 7, 999) - * ) - * //=> 12 - */ - function differenceInSeconds (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / 1000; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_seconds = differenceInSeconds; - - /** - * @category Week Helpers - * @summary Get the number of full weeks between the given dates. - * - * @description - * Get the number of full weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full weeks - * - * @example - * // How many full weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 2 - */ - function differenceInWeeks (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_days(dirtyDateLeft, dirtyDateRight) / 7; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_weeks = differenceInWeeks; - - /** - * @category Year Helpers - * @summary Get the number of full years between the given dates. - * - * @description - * Get the number of full years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full years - * - * @example - * // How many full years are between 31 December 2013 and 11 February 2015? - * var result = differenceInYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 1 - */ - function differenceInYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_years(dateLeft, dateRight)); - dateLeft.setFullYear(dateLeft.getFullYear() - sign * difference); - - // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full - // If so, result must be decreased by 1 in absolute value - var isLastYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastYearNotFull) - } - - var difference_in_years = differenceInYears; - - function buildDistanceInWordsLocale () { - var distanceInWordsLocale = { - lessThanXSeconds: { - one: 'less than a second', - other: 'less than {{count}} seconds' - }, - - xSeconds: { - one: '1 second', - other: '{{count}} seconds' - }, - - halfAMinute: 'half a minute', - - lessThanXMinutes: { - one: 'less than a minute', - other: 'less than {{count}} minutes' - }, - - xMinutes: { - one: '1 minute', - other: '{{count}} minutes' - }, - - aboutXHours: { - one: 'about 1 hour', - other: 'about {{count}} hours' - }, - - xHours: { - one: '1 hour', - other: '{{count}} hours' - }, - - xDays: { - one: '1 day', - other: '{{count}} days' - }, - - aboutXMonths: { - one: 'about 1 month', - other: 'about {{count}} months' - }, - - xMonths: { - one: '1 month', - other: '{{count}} months' - }, - - aboutXYears: { - one: 'about 1 year', - other: 'about {{count}} years' - }, - - xYears: { - one: '1 year', - other: '{{count}} years' - }, - - overXYears: { - one: 'over 1 year', - other: 'over {{count}} years' - }, - - almostXYears: { - one: 'almost 1 year', - other: 'almost {{count}} years' - } - }; - - function localize (token, count, options) { - options = options || {}; - - var result; - if (typeof distanceInWordsLocale[token] === 'string') { - result = distanceInWordsLocale[token]; - } else if (count === 1) { - result = distanceInWordsLocale[token].one; - } else { - result = distanceInWordsLocale[token].other.replace('{{count}}', count); - } - - if (options.addSuffix) { - if (options.comparison > 0) { - return 'in ' + result - } else { - return result + ' ago' - } - } - - return result - } - - return { - localize: localize - } - } - - var build_distance_in_words_locale = buildDistanceInWordsLocale; - - var commonFormatterKeys = [ - 'M', 'MM', 'Q', 'D', 'DD', 'DDD', 'DDDD', 'd', - 'E', 'W', 'WW', 'YY', 'YYYY', 'GG', 'GGGG', - 'H', 'HH', 'h', 'hh', 'm', 'mm', - 's', 'ss', 'S', 'SS', 'SSS', - 'Z', 'ZZ', 'X', 'x' - ]; - - function buildFormattingTokensRegExp (formatters) { - var formatterKeys = []; - for (var key in formatters) { - if (formatters.hasOwnProperty(key)) { - formatterKeys.push(key); - } - } - - var formattingTokens = commonFormatterKeys - .concat(formatterKeys) - .sort() - .reverse(); - var formattingTokensRegExp = new RegExp( - '(\\[[^\\[]*\\])|(\\\\)?' + '(' + formattingTokens.join('|') + '|.)', 'g' - ); - - return formattingTokensRegExp - } - - var build_formatting_tokens_reg_exp = buildFormattingTokensRegExp; - - function buildFormatLocale () { - // Note: in English, the names of days of the week and months are capitalized. - // If you are making a new locale based on this one, check if the same is true for the language you're working on. - // Generally, formatted dates should look like they are in the middle of a sentence, - // e.g. in Spanish language the weekdays and months should be in the lowercase. - var months3char = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var monthsFull = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; - var weekdays2char = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']; - var weekdays3char = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - var weekdaysFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; - var meridiemUppercase = ['AM', 'PM']; - var meridiemLowercase = ['am', 'pm']; - var meridiemFull = ['a.m.', 'p.m.']; - - var formatters = { - // Month: Jan, Feb, ..., Dec - 'MMM': function (date) { - return months3char[date.getMonth()] - }, - - // Month: January, February, ..., December - 'MMMM': function (date) { - return monthsFull[date.getMonth()] - }, - - // Day of week: Su, Mo, ..., Sa - 'dd': function (date) { - return weekdays2char[date.getDay()] - }, - - // Day of week: Sun, Mon, ..., Sat - 'ddd': function (date) { - return weekdays3char[date.getDay()] - }, - - // Day of week: Sunday, Monday, ..., Saturday - 'dddd': function (date) { - return weekdaysFull[date.getDay()] - }, - - // AM, PM - 'A': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemUppercase[1] : meridiemUppercase[0] - }, - - // am, pm - 'a': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemLowercase[1] : meridiemLowercase[0] - }, - - // a.m., p.m. - 'aa': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemFull[1] : meridiemFull[0] - } - }; - - // Generate ordinal version of formatters: M -> Mo, D -> Do, etc. - var ordinalFormatters = ['M', 'D', 'DDD', 'd', 'Q', 'W']; - ordinalFormatters.forEach(function (formatterToken) { - formatters[formatterToken + 'o'] = function (date, formatters) { - return ordinal(formatters[formatterToken](date)) - }; - }); - - return { - formatters: formatters, - formattingTokensRegExp: build_formatting_tokens_reg_exp(formatters) - } - } - - function ordinal (number) { - var rem100 = number % 100; - if (rem100 > 20 || rem100 < 10) { - switch (rem100 % 10) { - case 1: - return number + 'st' - case 2: - return number + 'nd' - case 3: - return number + 'rd' - } - } - return number + 'th' - } - - var build_format_locale = buildFormatLocale; - - /** - * @category Locales - * @summary English locale. - */ - var en = { - distanceInWords: build_distance_in_words_locale(), - format: build_format_locale() - }; - - var MINUTES_IN_DAY$1 = 1440; - var MINUTES_IN_ALMOST_TWO_DAYS = 2520; - var MINUTES_IN_MONTH$1 = 43200; - var MINUTES_IN_TWO_MONTHS = 86400; - - /** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words. - * - * | Distance between dates | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance between dates | Result | - * |------------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWords( - * new Date(2014, 6, 2), - * new Date(2015, 0, 1) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00, including seconds? - * var result = distanceInWords( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWords( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> 'about 1 year ago' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWords( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ - function distanceInWords (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = Math.round(seconds / 60) - offset; - var months; - - // 0 up to 2 mins - if (minutes < 2) { - if (options.includeSeconds) { - if (seconds < 5) { - return localize('lessThanXSeconds', 5, localizeOptions) - } else if (seconds < 10) { - return localize('lessThanXSeconds', 10, localizeOptions) - } else if (seconds < 20) { - return localize('lessThanXSeconds', 20, localizeOptions) - } else if (seconds < 40) { - return localize('halfAMinute', null, localizeOptions) - } else if (seconds < 60) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', 1, localizeOptions) - } - } else { - if (minutes === 0) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', minutes, localizeOptions) - } - } - - // 2 mins up to 0.75 hrs - } else if (minutes < 45) { - return localize('xMinutes', minutes, localizeOptions) - - // 0.75 hrs up to 1.5 hrs - } else if (minutes < 90) { - return localize('aboutXHours', 1, localizeOptions) - - // 1.5 hrs up to 24 hrs - } else if (minutes < MINUTES_IN_DAY$1) { - var hours = Math.round(minutes / 60); - return localize('aboutXHours', hours, localizeOptions) - - // 1 day up to 1.75 days - } else if (minutes < MINUTES_IN_ALMOST_TWO_DAYS) { - return localize('xDays', 1, localizeOptions) - - // 1.75 days up to 30 days - } else if (minutes < MINUTES_IN_MONTH$1) { - var days = Math.round(minutes / MINUTES_IN_DAY$1); - return localize('xDays', days, localizeOptions) - - // 1 month up to 2 months - } else if (minutes < MINUTES_IN_TWO_MONTHS) { - months = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('aboutXMonths', months, localizeOptions) - } - - months = difference_in_months(dateRight, dateLeft); - - // 2 months up to 12 months - if (months < 12) { - var nearestMonth = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('xMonths', nearestMonth, localizeOptions) - - // 1 year up to max Date - } else { - var monthsSinceStartOfYear = months % 12; - var years = Math.floor(months / 12); - - // N years up to 1 years 3 months - if (monthsSinceStartOfYear < 3) { - return localize('aboutXYears', years, localizeOptions) - - // N years 3 months up to N years 9 months - } else if (monthsSinceStartOfYear < 9) { - return localize('overXYears', years, localizeOptions) - - // N years 9 months up to N year 12 months - } else { - return localize('almostXYears', years + 1, localizeOptions) - } - } - } - - var distance_in_words = distanceInWords; - - var MINUTES_IN_DAY = 1440; - var MINUTES_IN_MONTH = 43200; - var MINUTES_IN_YEAR = 525600; - - /** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words, using strict units. - * This is like `distanceInWords`, but does not use helpers like 'almost', 'over', - * 'less than' and the like. - * - * | Distance between dates | Result | - * |------------------------|---------------------| - * | 0 ... 59 secs | [0..59] seconds | - * | 1 ... 59 mins | [1..59] minutes | - * | 1 ... 23 hrs | [1..23] hours | - * | 1 ... 29 days | [1..29] days | - * | 1 ... 11 months | [1..11] months | - * | 1 ... N years | [1..N] years | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {'s'|'m'|'h'|'d'|'M'|'Y'} [options.unit] - if specified, will force a unit - * @param {'floor'|'ceil'|'round'} [options.partialMethod='floor'] - which way to round partial units - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWordsStrict( - * new Date(2014, 6, 2), - * new Date(2015, 0, 2) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * ) - * //=> '15 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> '1 year ago' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, in minutes? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {unit: 'm'} - * ) - * //=> '525600 minutes' - * - * @example - * // What is the distance from 1 January 2016 - * // to 28 January 2015, in months, rounded up? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 28), - * new Date(2015, 0, 1), - * {unit: 'M', partialMethod: 'ceil'} - * ) - * //=> '1 month' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsStrict( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> '1 jaro' - */ - function distanceInWordsStrict (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var unit; - var mathPartial = Math[options.partialMethod ? String(options.partialMethod) : 'floor']; - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = mathPartial(seconds / 60) - offset; - var hours, days, months, years; - - if (options.unit) { - unit = String(options.unit); - } else { - if (minutes < 1) { - unit = 's'; - } else if (minutes < 60) { - unit = 'm'; - } else if (minutes < MINUTES_IN_DAY) { - unit = 'h'; - } else if (minutes < MINUTES_IN_MONTH) { - unit = 'd'; - } else if (minutes < MINUTES_IN_YEAR) { - unit = 'M'; - } else { - unit = 'Y'; - } - } - - // 0 up to 60 seconds - if (unit === 's') { - return localize('xSeconds', seconds, localizeOptions) - - // 1 up to 60 mins - } else if (unit === 'm') { - return localize('xMinutes', minutes, localizeOptions) - - // 1 up to 24 hours - } else if (unit === 'h') { - hours = mathPartial(minutes / 60); - return localize('xHours', hours, localizeOptions) - - // 1 up to 30 days - } else if (unit === 'd') { - days = mathPartial(minutes / MINUTES_IN_DAY); - return localize('xDays', days, localizeOptions) - - // 1 up to 12 months - } else if (unit === 'M') { - months = mathPartial(minutes / MINUTES_IN_MONTH); - return localize('xMonths', months, localizeOptions) - - // 1 year up to max Date - } else if (unit === 'Y') { - years = mathPartial(minutes / MINUTES_IN_YEAR); - return localize('xYears', years, localizeOptions) - } - - throw new Error('Unknown unit: ' + unit) - } - - var distance_in_words_strict = distanceInWordsStrict; - - /** - * @category Common Helpers - * @summary Return the distance between the given date and now in words. - * - * @description - * Return the distance between the given date and now in words. - * - * | Distance to now | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance to now | Result | - * |---------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} date - the given date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result specifies if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // If today is 1 January 2015, what is the distance to 2 July 2014? - * var result = distanceInWordsToNow( - * new Date(2014, 6, 2) - * ) - * //=> '6 months' - * - * @example - * // If now is 1 January 2015 00:00:00, - * // what is the distance to 1 January 2015 00:00:15, including seconds? - * var result = distanceInWordsToNow( - * new Date(2015, 0, 1, 0, 0, 15), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 January 2016, with a suffix? - * var result = distanceInWordsToNow( - * new Date(2016, 0, 1), - * {addSuffix: true} - * ) - * //=> 'in about 1 year' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 August 2016 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsToNow( - * new Date(2016, 7, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ - function distanceInWordsToNow (dirtyDate, dirtyOptions) { - return distance_in_words(Date.now(), dirtyDate, dirtyOptions) - } - - var distance_in_words_to_now = distanceInWordsToNow; - - /** - * @category Day Helpers - * @summary Return the array of dates within the specified range. - * - * @description - * Return the array of dates within the specified range. - * - * @param {Date|String|Number} startDate - the first date - * @param {Date|String|Number} endDate - the last date - * @param {Number} [step=1] - the step between each day - * @returns {Date[]} the array with starts of days from the day of startDate to the day of endDate - * @throws {Error} startDate cannot be after endDate - * - * @example - * // Each day between 6 October 2014 and 10 October 2014: - * var result = eachDay( - * new Date(2014, 9, 6), - * new Date(2014, 9, 10) - * ) - * //=> [ - * // Mon Oct 06 2014 00:00:00, - * // Tue Oct 07 2014 00:00:00, - * // Wed Oct 08 2014 00:00:00, - * // Thu Oct 09 2014 00:00:00, - * // Fri Oct 10 2014 00:00:00 - * // ] - */ - function eachDay (dirtyStartDate, dirtyEndDate, dirtyStep) { - var startDate = parse_1(dirtyStartDate); - var endDate = parse_1(dirtyEndDate); - var step = dirtyStep !== undefined ? dirtyStep : 1; - - var endTime = endDate.getTime(); - - if (startDate.getTime() > endTime) { - throw new Error('The first date cannot be after the second date') - } - - var dates = []; - - var currentDate = startDate; - currentDate.setHours(0, 0, 0, 0); - - while (currentDate.getTime() <= endTime) { - dates.push(parse_1(currentDate)); - currentDate.setDate(currentDate.getDate() + step); - } - - return dates - } - - var each_day = eachDay; - - /** - * @category Day Helpers - * @summary Return the end of a day for the given date. - * - * @description - * Return the end of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a day - * - * @example - * // The end of a day for 2 September 2014 11:55:00: - * var result = endOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 23:59:59.999 - */ - function endOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_day = endOfDay; - - /** - * @category Hour Helpers - * @summary Return the end of an hour for the given date. - * - * @description - * Return the end of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an hour - * - * @example - * // The end of an hour for 2 September 2014 11:55:00: - * var result = endOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:59:59.999 - */ - function endOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(59, 59, 999); - return date - } - - var end_of_hour = endOfHour; - - /** - * @category Week Helpers - * @summary Return the end of a week for the given date. - * - * @description - * Return the end of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the end of a week - * - * @example - * // The end of a week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 23:59:59.999 - * - * @example - * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 23:59:59.999 - */ - function endOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setDate(date.getDate() + diff); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_week = endOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the end of an ISO week for the given date. - * - * @description - * Return the end of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week - * - * @example - * // The end of an ISO week for 2 September 2014 11:55:00: - * var result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 23:59:59.999 - */ - function endOfISOWeek (dirtyDate) { - return end_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var end_of_iso_week = endOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the end of an ISO week-numbering year for the given date. - * - * @description - * Return the end of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The end of an ISO week-numbering year for 2 July 2005: - * var result = endOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 23:59:59.999 - */ - function endOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuaryOfNextYear); - date.setMilliseconds(date.getMilliseconds() - 1); - return date - } - - var end_of_iso_year = endOfISOYear; - - /** - * @category Minute Helpers - * @summary Return the end of a minute for the given date. - * - * @description - * Return the end of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a minute - * - * @example - * // The end of a minute for 1 December 2014 22:15:45.400: - * var result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:59.999 - */ - function endOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(59, 999); - return date - } - - var end_of_minute = endOfMinute; - - /** - * @category Month Helpers - * @summary Return the end of a month for the given date. - * - * @description - * Return the end of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a month - * - * @example - * // The end of a month for 2 September 2014 11:55:00: - * var result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ - function endOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_month = endOfMonth; - - /** - * @category Quarter Helpers - * @summary Return the end of a year quarter for the given date. - * - * @description - * Return the end of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a quarter - * - * @example - * // The end of a quarter for 2 September 2014 11:55:00: - * var result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ - function endOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_quarter = endOfQuarter; - - /** - * @category Second Helpers - * @summary Return the end of a second for the given date. - * - * @description - * Return the end of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a second - * - * @example - * // The end of a second for 1 December 2014 22:15:45.400: - * var result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.999 - */ - function endOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(999); - return date - } - - var end_of_second = endOfSecond; - - /** - * @category Day Helpers - * @summary Return the end of today. - * - * @description - * Return the end of today. - * - * @returns {Date} the end of today - * - * @example - * // If today is 6 October 2014: - * var result = endOfToday() - * //=> Mon Oct 6 2014 23:59:59.999 - */ - function endOfToday () { - return end_of_day(new Date()) - } - - var end_of_today = endOfToday; - - /** - * @category Day Helpers - * @summary Return the end of tomorrow. - * - * @description - * Return the end of tomorrow. - * - * @returns {Date} the end of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = endOfTomorrow() - * //=> Tue Oct 7 2014 23:59:59.999 - */ - function endOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_tomorrow = endOfTomorrow; - - /** - * @category Year Helpers - * @summary Return the end of a year for the given date. - * - * @description - * Return the end of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a year - * - * @example - * // The end of a year for 2 September 2014 11:55:00: - * var result = endOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 23:59:59.999 - */ - function endOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_year = endOfYear; - - /** - * @category Day Helpers - * @summary Return the end of yesterday. - * - * @description - * Return the end of yesterday. - * - * @returns {Date} the end of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = endOfYesterday() - * //=> Sun Oct 5 2014 23:59:59.999 - */ - function endOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_yesterday = endOfYesterday; - - /** - * @category Year Helpers - * @summary Return the start of a year for the given date. - * - * @description - * Return the start of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a year - * - * @example - * // The start of a year for 2 September 2014 11:55:00: - * var result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Jan 01 2014 00:00:00 - */ - function startOfYear (dirtyDate) { - var cleanDate = parse_1(dirtyDate); - var date = new Date(0); - date.setFullYear(cleanDate.getFullYear(), 0, 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_year = startOfYear; - - /** - * @category Day Helpers - * @summary Get the day of the year of the given date. - * - * @description - * Get the day of the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of year - * - * @example - * // Which day of the year is 2 July 2014? - * var result = getDayOfYear(new Date(2014, 6, 2)) - * //=> 183 - */ - function getDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = difference_in_calendar_days(date, start_of_year(date)); - var dayOfYear = diff + 1; - return dayOfYear - } - - var get_day_of_year = getDayOfYear; - - var MILLISECONDS_IN_WEEK$1 = 604800000; - - /** - * @category ISO Week Helpers - * @summary Get the ISO week of the given date. - * - * @description - * Get the ISO week of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week - * - * @example - * // Which week of the ISO-week numbering year is 2 January 2005? - * var result = getISOWeek(new Date(2005, 0, 2)) - * //=> 53 - */ - function getISOWeek (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = start_of_iso_week(date).getTime() - start_of_iso_year(date).getTime(); - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1 - } - - var get_iso_week = getISOWeek; - - /** - * @category Common Helpers - * @summary Is the given date valid? - * - * @description - * Returns false if argument is Invalid Date and true otherwise. - * Invalid Date is a Date, whose time value is NaN. - * - * Time value of Date: http://es5.github.io/#x15.9.1.1 - * - * @param {Date} date - the date to check - * @returns {Boolean} the date is valid - * @throws {TypeError} argument must be an instance of Date - * - * @example - * // For the valid date: - * var result = isValid(new Date(2014, 1, 31)) - * //=> true - * - * @example - * // For the invalid date: - * var result = isValid(new Date('')) - * //=> false - */ - function isValid (dirtyDate) { - if (is_date(dirtyDate)) { - return !isNaN(dirtyDate) - } else { - throw new TypeError(toString.call(dirtyDate) + ' is not an instance of Date') - } - } - - var is_valid = isValid; - - /** - * @category Common Helpers - * @summary Format the date. - * - * @description - * Return the formatted date string in the given format. - * - * Accepted tokens: - * | Unit | Token | Result examples | - * |-------------------------|-------|----------------------------------| - * | Month | M | 1, 2, ..., 12 | - * | | Mo | 1st, 2nd, ..., 12th | - * | | MM | 01, 02, ..., 12 | - * | | MMM | Jan, Feb, ..., Dec | - * | | MMMM | January, February, ..., December | - * | Quarter | Q | 1, 2, 3, 4 | - * | | Qo | 1st, 2nd, 3rd, 4th | - * | Day of month | D | 1, 2, ..., 31 | - * | | Do | 1st, 2nd, ..., 31st | - * | | DD | 01, 02, ..., 31 | - * | Day of year | DDD | 1, 2, ..., 366 | - * | | DDDo | 1st, 2nd, ..., 366th | - * | | DDDD | 001, 002, ..., 366 | - * | Day of week | d | 0, 1, ..., 6 | - * | | do | 0th, 1st, ..., 6th | - * | | dd | Su, Mo, ..., Sa | - * | | ddd | Sun, Mon, ..., Sat | - * | | dddd | Sunday, Monday, ..., Saturday | - * | Day of ISO week | E | 1, 2, ..., 7 | - * | ISO week | W | 1, 2, ..., 53 | - * | | Wo | 1st, 2nd, ..., 53rd | - * | | WW | 01, 02, ..., 53 | - * | Year | YY | 00, 01, ..., 99 | - * | | YYYY | 1900, 1901, ..., 2099 | - * | ISO week-numbering year | GG | 00, 01, ..., 99 | - * | | GGGG | 1900, 1901, ..., 2099 | - * | AM/PM | A | AM, PM | - * | | a | am, pm | - * | | aa | a.m., p.m. | - * | Hour | H | 0, 1, ... 23 | - * | | HH | 00, 01, ... 23 | - * | | h | 1, 2, ..., 12 | - * | | hh | 01, 02, ..., 12 | - * | Minute | m | 0, 1, ..., 59 | - * | | mm | 00, 01, ..., 59 | - * | Second | s | 0, 1, ..., 59 | - * | | ss | 00, 01, ..., 59 | - * | 1/10 of second | S | 0, 1, ..., 9 | - * | 1/100 of second | SS | 00, 01, ..., 99 | - * | Millisecond | SSS | 000, 001, ..., 999 | - * | Timezone | Z | -01:00, +00:00, ... +12:00 | - * | | ZZ | -0100, +0000, ..., +1200 | - * | Seconds timestamp | X | 512969520 | - * | Milliseconds timestamp | x | 512969520900 | - * - * The characters wrapped in square brackets are escaped. - * - * The result may vary by locale. - * - * @param {Date|String|Number} date - the original date - * @param {String} [format='YYYY-MM-DDTHH:mm:ss.SSSZ'] - the string of tokens - * @param {Object} [options] - the object with options - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the formatted date string - * - * @example - * // Represent 11 February 2014 in middle-endian format: - * var result = format( - * new Date(2014, 1, 11), - * 'MM/DD/YYYY' - * ) - * //=> '02/11/2014' - * - * @example - * // Represent 2 July 2014 in Esperanto: - * var eoLocale = require('date-fns/locale/eo') - * var result = format( - * new Date(2014, 6, 2), - * 'Do [de] MMMM YYYY', - * {locale: eoLocale} - * ) - * //=> '2-a de julio 2014' - */ - function format (dirtyDate, dirtyFormatStr, dirtyOptions) { - var formatStr = dirtyFormatStr ? String(dirtyFormatStr) : 'YYYY-MM-DDTHH:mm:ss.SSSZ'; - var options = dirtyOptions || {}; - - var locale = options.locale; - var localeFormatters = en.format.formatters; - var formattingTokensRegExp = en.format.formattingTokensRegExp; - if (locale && locale.format && locale.format.formatters) { - localeFormatters = locale.format.formatters; - - if (locale.format.formattingTokensRegExp) { - formattingTokensRegExp = locale.format.formattingTokensRegExp; - } - } - - var date = parse_1(dirtyDate); - - if (!is_valid(date)) { - return 'Invalid Date' - } - - var formatFn = buildFormatFn(formatStr, localeFormatters, formattingTokensRegExp); - - return formatFn(date) - } - - var formatters = { - // Month: 1, 2, ..., 12 - 'M': function (date) { - return date.getMonth() + 1 - }, - - // Month: 01, 02, ..., 12 - 'MM': function (date) { - return addLeadingZeros(date.getMonth() + 1, 2) - }, - - // Quarter: 1, 2, 3, 4 - 'Q': function (date) { - return Math.ceil((date.getMonth() + 1) / 3) - }, - - // Day of month: 1, 2, ..., 31 - 'D': function (date) { - return date.getDate() - }, - - // Day of month: 01, 02, ..., 31 - 'DD': function (date) { - return addLeadingZeros(date.getDate(), 2) - }, - - // Day of year: 1, 2, ..., 366 - 'DDD': function (date) { - return get_day_of_year(date) - }, - - // Day of year: 001, 002, ..., 366 - 'DDDD': function (date) { - return addLeadingZeros(get_day_of_year(date), 3) - }, - - // Day of week: 0, 1, ..., 6 - 'd': function (date) { - return date.getDay() - }, - - // Day of ISO week: 1, 2, ..., 7 - 'E': function (date) { - return date.getDay() || 7 - }, - - // ISO week: 1, 2, ..., 53 - 'W': function (date) { - return get_iso_week(date) - }, - - // ISO week: 01, 02, ..., 53 - 'WW': function (date) { - return addLeadingZeros(get_iso_week(date), 2) - }, - - // Year: 00, 01, ..., 99 - 'YY': function (date) { - return addLeadingZeros(date.getFullYear(), 4).substr(2) - }, - - // Year: 1900, 1901, ..., 2099 - 'YYYY': function (date) { - return addLeadingZeros(date.getFullYear(), 4) - }, - - // ISO week-numbering year: 00, 01, ..., 99 - 'GG': function (date) { - return String(get_iso_year(date)).substr(2) - }, - - // ISO week-numbering year: 1900, 1901, ..., 2099 - 'GGGG': function (date) { - return get_iso_year(date) - }, - - // Hour: 0, 1, ... 23 - 'H': function (date) { - return date.getHours() - }, - - // Hour: 00, 01, ..., 23 - 'HH': function (date) { - return addLeadingZeros(date.getHours(), 2) - }, - - // Hour: 1, 2, ..., 12 - 'h': function (date) { - var hours = date.getHours(); - if (hours === 0) { - return 12 - } else if (hours > 12) { - return hours % 12 - } else { - return hours - } - }, - - // Hour: 01, 02, ..., 12 - 'hh': function (date) { - return addLeadingZeros(formatters['h'](date), 2) - }, - - // Minute: 0, 1, ..., 59 - 'm': function (date) { - return date.getMinutes() - }, - - // Minute: 00, 01, ..., 59 - 'mm': function (date) { - return addLeadingZeros(date.getMinutes(), 2) - }, - - // Second: 0, 1, ..., 59 - 's': function (date) { - return date.getSeconds() - }, - - // Second: 00, 01, ..., 59 - 'ss': function (date) { - return addLeadingZeros(date.getSeconds(), 2) - }, - - // 1/10 of second: 0, 1, ..., 9 - 'S': function (date) { - return Math.floor(date.getMilliseconds() / 100) - }, - - // 1/100 of second: 00, 01, ..., 99 - 'SS': function (date) { - return addLeadingZeros(Math.floor(date.getMilliseconds() / 10), 2) - }, - - // Millisecond: 000, 001, ..., 999 - 'SSS': function (date) { - return addLeadingZeros(date.getMilliseconds(), 3) - }, - - // Timezone: -01:00, +00:00, ... +12:00 - 'Z': function (date) { - return formatTimezone(date.getTimezoneOffset(), ':') - }, - - // Timezone: -0100, +0000, ... +1200 - 'ZZ': function (date) { - return formatTimezone(date.getTimezoneOffset()) - }, - - // Seconds timestamp: 512969520 - 'X': function (date) { - return Math.floor(date.getTime() / 1000) - }, - - // Milliseconds timestamp: 512969520900 - 'x': function (date) { - return date.getTime() - } - }; - - function buildFormatFn (formatStr, localeFormatters, formattingTokensRegExp) { - var array = formatStr.match(formattingTokensRegExp); - var length = array.length; - - var i; - var formatter; - for (i = 0; i < length; i++) { - formatter = localeFormatters[array[i]] || formatters[array[i]]; - if (formatter) { - array[i] = formatter; - } else { - array[i] = removeFormattingTokens(array[i]); - } - } - - return function (date) { - var output = ''; - for (var i = 0; i < length; i++) { - if (array[i] instanceof Function) { - output += array[i](date, formatters); - } else { - output += array[i]; - } - } - return output - } - } - - function removeFormattingTokens (input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|]$/g, '') - } - return input.replace(/\\/g, '') - } - - function formatTimezone (offset, delimeter) { - delimeter = delimeter || ''; - var sign = offset > 0 ? '-' : '+'; - var absOffset = Math.abs(offset); - var hours = Math.floor(absOffset / 60); - var minutes = absOffset % 60; - return sign + addLeadingZeros(hours, 2) + delimeter + addLeadingZeros(minutes, 2) - } - - function addLeadingZeros (number, targetLength) { - var output = Math.abs(number).toString(); - while (output.length < targetLength) { - output = '0' + output; - } - return output - } - - var format_1 = format; - - /** - * @category Day Helpers - * @summary Get the day of the month of the given date. - * - * @description - * Get the day of the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of month - * - * @example - * // Which day of the month is 29 February 2012? - * var result = getDate(new Date(2012, 1, 29)) - * //=> 29 - */ - function getDate (dirtyDate) { - var date = parse_1(dirtyDate); - var dayOfMonth = date.getDate(); - return dayOfMonth - } - - var get_date = getDate; - - /** - * @category Weekday Helpers - * @summary Get the day of the week of the given date. - * - * @description - * Get the day of the week of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of week - * - * @example - * // Which day of the week is 29 February 2012? - * var result = getDay(new Date(2012, 1, 29)) - * //=> 3 - */ - function getDay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day - } - - var get_day = getDay; - - /** - * @category Year Helpers - * @summary Is the given date in the leap year? - * - * @description - * Is the given date in the leap year? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the leap year - * - * @example - * // Is 1 September 2012 in the leap year? - * var result = isLeapYear(new Date(2012, 8, 1)) - * //=> true - */ - function isLeapYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0 - } - - var is_leap_year = isLeapYear; - - /** - * @category Year Helpers - * @summary Get the number of days in a year of the given date. - * - * @description - * Get the number of days in a year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a year - * - * @example - * // How many days are in 2012? - * var result = getDaysInYear(new Date(2012, 0, 1)) - * //=> 366 - */ - function getDaysInYear (dirtyDate) { - return is_leap_year(dirtyDate) ? 366 : 365 - } - - var get_days_in_year = getDaysInYear; - - /** - * @category Hour Helpers - * @summary Get the hours of the given date. - * - * @description - * Get the hours of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the hours - * - * @example - * // Get the hours of 29 February 2012 11:45:00: - * var result = getHours(new Date(2012, 1, 29, 11, 45)) - * //=> 11 - */ - function getHours (dirtyDate) { - var date = parse_1(dirtyDate); - var hours = date.getHours(); - return hours - } - - var get_hours = getHours; - - /** - * @category Weekday Helpers - * @summary Get the day of the ISO week of the given date. - * - * @description - * Get the day of the ISO week of the given date, - * which is 7 for Sunday, 1 for Monday etc. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of ISO week - * - * @example - * // Which day of the ISO week is 26 February 2012? - * var result = getISODay(new Date(2012, 1, 26)) - * //=> 7 - */ - function getISODay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - - if (day === 0) { - day = 7; - } - - return day - } - - var get_iso_day = getISODay; - - var MILLISECONDS_IN_WEEK = 604800000; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of weeks in an ISO week-numbering year of the given date. - * - * @description - * Get the number of weeks in an ISO week-numbering year of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of ISO weeks in a year - * - * @example - * // How many weeks are in ISO week-numbering year 2015? - * var result = getISOWeeksInYear(new Date(2015, 1, 11)) - * //=> 53 - */ - function getISOWeeksInYear (dirtyDate) { - var thisYear = start_of_iso_year(dirtyDate); - var nextYear = start_of_iso_year(add_weeks(thisYear, 60)); - var diff = nextYear.valueOf() - thisYear.valueOf(); - // Round the number of weeks to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK) - } - - var get_iso_weeks_in_year = getISOWeeksInYear; - - /** - * @category Millisecond Helpers - * @summary Get the milliseconds of the given date. - * - * @description - * Get the milliseconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the milliseconds - * - * @example - * // Get the milliseconds of 29 February 2012 11:45:05.123: - * var result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 123 - */ - function getMilliseconds (dirtyDate) { - var date = parse_1(dirtyDate); - var milliseconds = date.getMilliseconds(); - return milliseconds - } - - var get_milliseconds = getMilliseconds; - - /** - * @category Minute Helpers - * @summary Get the minutes of the given date. - * - * @description - * Get the minutes of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the minutes - * - * @example - * // Get the minutes of 29 February 2012 11:45:05: - * var result = getMinutes(new Date(2012, 1, 29, 11, 45, 5)) - * //=> 45 - */ - function getMinutes (dirtyDate) { - var date = parse_1(dirtyDate); - var minutes = date.getMinutes(); - return minutes - } - - var get_minutes = getMinutes; - - /** - * @category Month Helpers - * @summary Get the month of the given date. - * - * @description - * Get the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the month - * - * @example - * // Which month is 29 February 2012? - * var result = getMonth(new Date(2012, 1, 29)) - * //=> 1 - */ - function getMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - return month - } - - var get_month = getMonth; - - var MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000; - - /** - * @category Range Helpers - * @summary Get the number of days that overlap in two date ranges - * - * @description - * Get the number of days that overlap in two date ranges - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Number} the number of days that overlap in two date ranges - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges adds 1 for each started overlapping day: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> 3 - * - * @example - * // For non-overlapping date ranges returns 0: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> 0 - */ - function getOverlappingDaysInRanges (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - var isOverlapping = initialStartTime < comparedEndTime && comparedStartTime < initialEndTime; - - if (!isOverlapping) { - return 0 - } - - var overlapStartDate = comparedStartTime < initialStartTime - ? initialStartTime - : comparedStartTime; - - var overlapEndDate = comparedEndTime > initialEndTime - ? initialEndTime - : comparedEndTime; - - var differenceInMs = overlapEndDate - overlapStartDate; - - return Math.ceil(differenceInMs / MILLISECONDS_IN_DAY) - } - - var get_overlapping_days_in_ranges = getOverlappingDaysInRanges; - - /** - * @category Second Helpers - * @summary Get the seconds of the given date. - * - * @description - * Get the seconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the seconds - * - * @example - * // Get the seconds of 29 February 2012 11:45:05.123: - * var result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 5 - */ - function getSeconds (dirtyDate) { - var date = parse_1(dirtyDate); - var seconds = date.getSeconds(); - return seconds - } - - var get_seconds = getSeconds; - - /** - * @category Timestamp Helpers - * @summary Get the milliseconds timestamp of the given date. - * - * @description - * Get the milliseconds timestamp of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the timestamp - * - * @example - * // Get the timestamp of 29 February 2012 11:45:05.123: - * var result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 1330515905123 - */ - function getTime (dirtyDate) { - var date = parse_1(dirtyDate); - var timestamp = date.getTime(); - return timestamp - } - - var get_time = getTime; - - /** - * @category Year Helpers - * @summary Get the year of the given date. - * - * @description - * Get the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the year - * - * @example - * // Which year is 2 July 2014? - * var result = getYear(new Date(2014, 6, 2)) - * //=> 2014 - */ - function getYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year - } - - var get_year = getYear; - - /** - * @category Common Helpers - * @summary Is the first date after the second one? - * - * @description - * Is the first date after the second one? - * - * @param {Date|String|Number} date - the date that should be after the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is after the second date - * - * @example - * // Is 10 July 1989 after 11 February 1987? - * var result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> true - */ - function isAfter (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() > dateToCompare.getTime() - } - - var is_after = isAfter; - - /** - * @category Common Helpers - * @summary Is the first date before the second one? - * - * @description - * Is the first date before the second one? - * - * @param {Date|String|Number} date - the date that should be before the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is before the second date - * - * @example - * // Is 10 July 1989 before 11 February 1987? - * var result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> false - */ - function isBefore (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() < dateToCompare.getTime() - } - - var is_before = isBefore; - - /** - * @category Common Helpers - * @summary Are the given dates equal? - * - * @description - * Are the given dates equal? - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Boolean} the dates are equal - * - * @example - * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal? - * var result = isEqual( - * new Date(2014, 6, 2, 6, 30, 45, 0) - * new Date(2014, 6, 2, 6, 30, 45, 500) - * ) - * //=> false - */ - function isEqual (dirtyLeftDate, dirtyRightDate) { - var dateLeft = parse_1(dirtyLeftDate); - var dateRight = parse_1(dirtyRightDate); - return dateLeft.getTime() === dateRight.getTime() - } - - var is_equal = isEqual; - - /** - * @category Month Helpers - * @summary Is the given date the first day of a month? - * - * @description - * Is the given date the first day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the first day of a month - * - * @example - * // Is 1 September 2014 the first day of a month? - * var result = isFirstDayOfMonth(new Date(2014, 8, 1)) - * //=> true - */ - function isFirstDayOfMonth (dirtyDate) { - return parse_1(dirtyDate).getDate() === 1 - } - - var is_first_day_of_month = isFirstDayOfMonth; - - /** - * @category Weekday Helpers - * @summary Is the given date Friday? - * - * @description - * Is the given date Friday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Friday - * - * @example - * // Is 26 September 2014 Friday? - * var result = isFriday(new Date(2014, 8, 26)) - * //=> true - */ - function isFriday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 5 - } - - var is_friday = isFriday; - - /** - * @category Common Helpers - * @summary Is the given date in the future? - * - * @description - * Is the given date in the future? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the future - * - * @example - * // If today is 6 October 2014, is 31 December 2014 in the future? - * var result = isFuture(new Date(2014, 11, 31)) - * //=> true - */ - function isFuture (dirtyDate) { - return parse_1(dirtyDate).getTime() > new Date().getTime() - } - - var is_future = isFuture; - - /** - * @category Month Helpers - * @summary Is the given date the last day of a month? - * - * @description - * Is the given date the last day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the last day of a month - * - * @example - * // Is 28 February 2014 the last day of a month? - * var result = isLastDayOfMonth(new Date(2014, 1, 28)) - * //=> true - */ - function isLastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - return end_of_day(date).getTime() === end_of_month(date).getTime() - } - - var is_last_day_of_month = isLastDayOfMonth; - - /** - * @category Weekday Helpers - * @summary Is the given date Monday? - * - * @description - * Is the given date Monday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Monday - * - * @example - * // Is 22 September 2014 Monday? - * var result = isMonday(new Date(2014, 8, 22)) - * //=> true - */ - function isMonday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 1 - } - - var is_monday = isMonday; - - /** - * @category Common Helpers - * @summary Is the given date in the past? - * - * @description - * Is the given date in the past? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the past - * - * @example - * // If today is 6 October 2014, is 2 July 2014 in the past? - * var result = isPast(new Date(2014, 6, 2)) - * //=> true - */ - function isPast (dirtyDate) { - return parse_1(dirtyDate).getTime() < new Date().getTime() - } - - var is_past = isPast; - - /** - * @category Day Helpers - * @summary Are the given dates in the same day? - * - * @description - * Are the given dates in the same day? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same day - * - * @example - * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? - * var result = isSameDay( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 18, 0) - * ) - * //=> true - */ - function isSameDay (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfDay = start_of_day(dirtyDateLeft); - var dateRightStartOfDay = start_of_day(dirtyDateRight); - - return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime() - } - - var is_same_day = isSameDay; - - /** - * @category Hour Helpers - * @summary Return the start of an hour for the given date. - * - * @description - * Return the start of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an hour - * - * @example - * // The start of an hour for 2 September 2014 11:55:00: - * var result = startOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:00:00 - */ - function startOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(0, 0, 0); - return date - } - - var start_of_hour = startOfHour; - - /** - * @category Hour Helpers - * @summary Are the given dates in the same hour? - * - * @description - * Are the given dates in the same hour? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same hour - * - * @example - * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour? - * var result = isSameHour( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 6, 30) - * ) - * //=> true - */ - function isSameHour (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfHour = start_of_hour(dirtyDateLeft); - var dateRightStartOfHour = start_of_hour(dirtyDateRight); - - return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime() - } - - var is_same_hour = isSameHour; - - /** - * @category Week Helpers - * @summary Are the given dates in the same week? - * - * @description - * Are the given dates in the same week? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the dates are in the same week - * - * @example - * // Are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4) - * ) - * //=> true - * - * @example - * // If week starts with Monday, - * // are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4), - * {weekStartsOn: 1} - * ) - * //=> false - */ - function isSameWeek (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var dateLeftStartOfWeek = start_of_week(dirtyDateLeft, dirtyOptions); - var dateRightStartOfWeek = start_of_week(dirtyDateRight, dirtyOptions); - - return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime() - } - - var is_same_week = isSameWeek; - - /** - * @category ISO Week Helpers - * @summary Are the given dates in the same ISO week? - * - * @description - * Are the given dates in the same ISO week? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week - * - * @example - * // Are 1 September 2014 and 7 September 2014 in the same ISO week? - * var result = isSameISOWeek( - * new Date(2014, 8, 1), - * new Date(2014, 8, 7) - * ) - * //=> true - */ - function isSameISOWeek (dirtyDateLeft, dirtyDateRight) { - return is_same_week(dirtyDateLeft, dirtyDateRight, {weekStartsOn: 1}) - } - - var is_same_iso_week = isSameISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Are the given dates in the same ISO week-numbering year? - * - * @description - * Are the given dates in the same ISO week-numbering year? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week-numbering year - * - * @example - * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? - * var result = isSameISOYear( - * new Date(2003, 11, 29), - * new Date(2005, 0, 2) - * ) - * //=> true - */ - function isSameISOYear (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfYear = start_of_iso_year(dirtyDateLeft); - var dateRightStartOfYear = start_of_iso_year(dirtyDateRight); - - return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime() - } - - var is_same_iso_year = isSameISOYear; - - /** - * @category Minute Helpers - * @summary Return the start of a minute for the given date. - * - * @description - * Return the start of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a minute - * - * @example - * // The start of a minute for 1 December 2014 22:15:45.400: - * var result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:00 - */ - function startOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(0, 0); - return date - } - - var start_of_minute = startOfMinute; - - /** - * @category Minute Helpers - * @summary Are the given dates in the same minute? - * - * @description - * Are the given dates in the same minute? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same minute - * - * @example - * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 - * // in the same minute? - * var result = isSameMinute( - * new Date(2014, 8, 4, 6, 30), - * new Date(2014, 8, 4, 6, 30, 15) - * ) - * //=> true - */ - function isSameMinute (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfMinute = start_of_minute(dirtyDateLeft); - var dateRightStartOfMinute = start_of_minute(dirtyDateRight); - - return dateLeftStartOfMinute.getTime() === dateRightStartOfMinute.getTime() - } - - var is_same_minute = isSameMinute; - - /** - * @category Month Helpers - * @summary Are the given dates in the same month? - * - * @description - * Are the given dates in the same month? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same month - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same month? - * var result = isSameMonth( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ - function isSameMonth (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() && - dateLeft.getMonth() === dateRight.getMonth() - } - - var is_same_month = isSameMonth; - - /** - * @category Quarter Helpers - * @summary Return the start of a year quarter for the given date. - * - * @description - * Return the start of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a quarter - * - * @example - * // The start of a quarter for 2 September 2014 11:55:00: - * var result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Jul 01 2014 00:00:00 - */ - function startOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3; - date.setMonth(month, 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_quarter = startOfQuarter; - - /** - * @category Quarter Helpers - * @summary Are the given dates in the same year quarter? - * - * @description - * Are the given dates in the same year quarter? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same quarter - * - * @example - * // Are 1 January 2014 and 8 March 2014 in the same quarter? - * var result = isSameQuarter( - * new Date(2014, 0, 1), - * new Date(2014, 2, 8) - * ) - * //=> true - */ - function isSameQuarter (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfQuarter = start_of_quarter(dirtyDateLeft); - var dateRightStartOfQuarter = start_of_quarter(dirtyDateRight); - - return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime() - } - - var is_same_quarter = isSameQuarter; - - /** - * @category Second Helpers - * @summary Return the start of a second for the given date. - * - * @description - * Return the start of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a second - * - * @example - * // The start of a second for 1 December 2014 22:15:45.400: - * var result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.000 - */ - function startOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(0); - return date - } - - var start_of_second = startOfSecond; - - /** - * @category Second Helpers - * @summary Are the given dates in the same second? - * - * @description - * Are the given dates in the same second? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same second - * - * @example - * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 - * // in the same second? - * var result = isSameSecond( - * new Date(2014, 8, 4, 6, 30, 15), - * new Date(2014, 8, 4, 6, 30, 15, 500) - * ) - * //=> true - */ - function isSameSecond (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfSecond = start_of_second(dirtyDateLeft); - var dateRightStartOfSecond = start_of_second(dirtyDateRight); - - return dateLeftStartOfSecond.getTime() === dateRightStartOfSecond.getTime() - } - - var is_same_second = isSameSecond; - - /** - * @category Year Helpers - * @summary Are the given dates in the same year? - * - * @description - * Are the given dates in the same year? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same year - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same year? - * var result = isSameYear( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ - function isSameYear (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() - } - - var is_same_year = isSameYear; - - /** - * @category Weekday Helpers - * @summary Is the given date Saturday? - * - * @description - * Is the given date Saturday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Saturday - * - * @example - * // Is 27 September 2014 Saturday? - * var result = isSaturday(new Date(2014, 8, 27)) - * //=> true - */ - function isSaturday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 6 - } - - var is_saturday = isSaturday; - - /** - * @category Weekday Helpers - * @summary Is the given date Sunday? - * - * @description - * Is the given date Sunday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Sunday - * - * @example - * // Is 21 September 2014 Sunday? - * var result = isSunday(new Date(2014, 8, 21)) - * //=> true - */ - function isSunday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 0 - } - - var is_sunday = isSunday; - - /** - * @category Hour Helpers - * @summary Is the given date in the same hour as the current date? - * - * @description - * Is the given date in the same hour as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this hour - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:00:00 in this hour? - * var result = isThisHour(new Date(2014, 8, 25, 18)) - * //=> true - */ - function isThisHour (dirtyDate) { - return is_same_hour(new Date(), dirtyDate) - } - - var is_this_hour = isThisHour; - - /** - * @category ISO Week Helpers - * @summary Is the given date in the same ISO week as the current date? - * - * @description - * Is the given date in the same ISO week as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week - * - * @example - * // If today is 25 September 2014, is 22 September 2014 in this ISO week? - * var result = isThisISOWeek(new Date(2014, 8, 22)) - * //=> true - */ - function isThisISOWeek (dirtyDate) { - return is_same_iso_week(new Date(), dirtyDate) - } - - var is_this_iso_week = isThisISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Is the given date in the same ISO week-numbering year as the current date? - * - * @description - * Is the given date in the same ISO week-numbering year as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week-numbering year - * - * @example - * // If today is 25 September 2014, - * // is 30 December 2013 in this ISO week-numbering year? - * var result = isThisISOYear(new Date(2013, 11, 30)) - * //=> true - */ - function isThisISOYear (dirtyDate) { - return is_same_iso_year(new Date(), dirtyDate) - } - - var is_this_iso_year = isThisISOYear; - - /** - * @category Minute Helpers - * @summary Is the given date in the same minute as the current date? - * - * @description - * Is the given date in the same minute as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this minute - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:00 in this minute? - * var result = isThisMinute(new Date(2014, 8, 25, 18, 30)) - * //=> true - */ - function isThisMinute (dirtyDate) { - return is_same_minute(new Date(), dirtyDate) - } - - var is_this_minute = isThisMinute; - - /** - * @category Month Helpers - * @summary Is the given date in the same month as the current date? - * - * @description - * Is the given date in the same month as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this month - * - * @example - * // If today is 25 September 2014, is 15 September 2014 in this month? - * var result = isThisMonth(new Date(2014, 8, 15)) - * //=> true - */ - function isThisMonth (dirtyDate) { - return is_same_month(new Date(), dirtyDate) - } - - var is_this_month = isThisMonth; - - /** - * @category Quarter Helpers - * @summary Is the given date in the same quarter as the current date? - * - * @description - * Is the given date in the same quarter as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this quarter - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this quarter? - * var result = isThisQuarter(new Date(2014, 6, 2)) - * //=> true - */ - function isThisQuarter (dirtyDate) { - return is_same_quarter(new Date(), dirtyDate) - } - - var is_this_quarter = isThisQuarter; - - /** - * @category Second Helpers - * @summary Is the given date in the same second as the current date? - * - * @description - * Is the given date in the same second as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this second - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:15.000 in this second? - * var result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15)) - * //=> true - */ - function isThisSecond (dirtyDate) { - return is_same_second(new Date(), dirtyDate) - } - - var is_this_second = isThisSecond; - - /** - * @category Week Helpers - * @summary Is the given date in the same week as the current date? - * - * @description - * Is the given date in the same week as the current date? - * - * @param {Date|String|Number} date - the date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the date is in this week - * - * @example - * // If today is 25 September 2014, is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21)) - * //=> true - * - * @example - * // If today is 25 September 2014 and week starts with Monday - * // is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21), {weekStartsOn: 1}) - * //=> false - */ - function isThisWeek (dirtyDate, dirtyOptions) { - return is_same_week(new Date(), dirtyDate, dirtyOptions) - } - - var is_this_week = isThisWeek; - - /** - * @category Year Helpers - * @summary Is the given date in the same year as the current date? - * - * @description - * Is the given date in the same year as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this year - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this year? - * var result = isThisYear(new Date(2014, 6, 2)) - * //=> true - */ - function isThisYear (dirtyDate) { - return is_same_year(new Date(), dirtyDate) - } - - var is_this_year = isThisYear; - - /** - * @category Weekday Helpers - * @summary Is the given date Thursday? - * - * @description - * Is the given date Thursday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Thursday - * - * @example - * // Is 25 September 2014 Thursday? - * var result = isThursday(new Date(2014, 8, 25)) - * //=> true - */ - function isThursday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 4 - } - - var is_thursday = isThursday; - - /** - * @category Day Helpers - * @summary Is the given date today? - * - * @description - * Is the given date today? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is today - * - * @example - * // If today is 6 October 2014, is 6 October 14:00:00 today? - * var result = isToday(new Date(2014, 9, 6, 14, 0)) - * //=> true - */ - function isToday (dirtyDate) { - return start_of_day(dirtyDate).getTime() === start_of_day(new Date()).getTime() - } - - var is_today = isToday; - - /** - * @category Day Helpers - * @summary Is the given date tomorrow? - * - * @description - * Is the given date tomorrow? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is tomorrow - * - * @example - * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow? - * var result = isTomorrow(new Date(2014, 9, 7, 14, 0)) - * //=> true - */ - function isTomorrow (dirtyDate) { - var tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 1); - return start_of_day(dirtyDate).getTime() === start_of_day(tomorrow).getTime() - } - - var is_tomorrow = isTomorrow; - - /** - * @category Weekday Helpers - * @summary Is the given date Tuesday? - * - * @description - * Is the given date Tuesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Tuesday - * - * @example - * // Is 23 September 2014 Tuesday? - * var result = isTuesday(new Date(2014, 8, 23)) - * //=> true - */ - function isTuesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 2 - } - - var is_tuesday = isTuesday; - - /** - * @category Weekday Helpers - * @summary Is the given date Wednesday? - * - * @description - * Is the given date Wednesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Wednesday - * - * @example - * // Is 24 September 2014 Wednesday? - * var result = isWednesday(new Date(2014, 8, 24)) - * //=> true - */ - function isWednesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 3 - } - - var is_wednesday = isWednesday; - - /** - * @category Weekday Helpers - * @summary Does the given date fall on a weekend? - * - * @description - * Does the given date fall on a weekend? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date falls on a weekend - * - * @example - * // Does 5 October 2014 fall on a weekend? - * var result = isWeekend(new Date(2014, 9, 5)) - * //=> true - */ - function isWeekend (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day === 0 || day === 6 - } - - var is_weekend = isWeekend; - - /** - * @category Range Helpers - * @summary Is the given date within the range? - * - * @description - * Is the given date within the range? - * - * @param {Date|String|Number} date - the date to check - * @param {Date|String|Number} startDate - the start of range - * @param {Date|String|Number} endDate - the end of range - * @returns {Boolean} the date is within the range - * @throws {Error} startDate cannot be after endDate - * - * @example - * // For the date within the range: - * isWithinRange( - * new Date(2014, 0, 3), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> true - * - * @example - * // For the date outside of the range: - * isWithinRange( - * new Date(2014, 0, 10), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> false - */ - function isWithinRange (dirtyDate, dirtyStartDate, dirtyEndDate) { - var time = parse_1(dirtyDate).getTime(); - var startTime = parse_1(dirtyStartDate).getTime(); - var endTime = parse_1(dirtyEndDate).getTime(); - - if (startTime > endTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return time >= startTime && time <= endTime - } - - var is_within_range = isWithinRange; - - /** - * @category Day Helpers - * @summary Is the given date yesterday? - * - * @description - * Is the given date yesterday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is yesterday - * - * @example - * // If today is 6 October 2014, is 5 October 14:00:00 yesterday? - * var result = isYesterday(new Date(2014, 9, 5, 14, 0)) - * //=> true - */ - function isYesterday (dirtyDate) { - var yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - return start_of_day(dirtyDate).getTime() === start_of_day(yesterday).getTime() - } - - var is_yesterday = isYesterday; - - /** - * @category Week Helpers - * @summary Return the last day of a week for the given date. - * - * @description - * Return the last day of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the last day of a week - * - * @example - * // The last day of a week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ - function lastDayOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setHours(0, 0, 0, 0); - date.setDate(date.getDate() + diff); - return date - } - - var last_day_of_week = lastDayOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the last day of an ISO week for the given date. - * - * @description - * Return the last day of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of an ISO week - * - * @example - * // The last day of an ISO week for 2 September 2014 11:55:00: - * var result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 00:00:00 - */ - function lastDayOfISOWeek (dirtyDate) { - return last_day_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var last_day_of_iso_week = lastDayOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the last day of an ISO week-numbering year for the given date. - * - * @description - * Return the last day of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The last day of an ISO week-numbering year for 2 July 2005: - * var result = lastDayOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 00:00:00 - */ - function lastDayOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year + 1, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - date.setDate(date.getDate() - 1); - return date - } - - var last_day_of_iso_year = lastDayOfISOYear; - - /** - * @category Month Helpers - * @summary Return the last day of a month for the given date. - * - * @description - * Return the last day of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a month - * - * @example - * // The last day of a month for 2 September 2014 11:55:00: - * var result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ - function lastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_month = lastDayOfMonth; - - /** - * @category Quarter Helpers - * @summary Return the last day of a year quarter for the given date. - * - * @description - * Return the last day of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a quarter - * - * @example - * // The last day of a quarter for 2 September 2014 11:55:00: - * var result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ - function lastDayOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_quarter = lastDayOfQuarter; - - /** - * @category Year Helpers - * @summary Return the last day of a year for the given date. - * - * @description - * Return the last day of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a year - * - * @example - * // The last day of a year for 2 September 2014 11:55:00: - * var result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 00:00:00 - */ - function lastDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_year = lastDayOfYear; - - /** - * @category Common Helpers - * @summary Return the latest of the given dates. - * - * @description - * Return the latest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the latest of the dates - * - * @example - * // Which of these dates is the latest? - * var result = max( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Sun Jul 02 1995 00:00:00 - */ - function max () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var latestTimestamp = Math.max.apply(null, dates); - return new Date(latestTimestamp) - } - - var max_1 = max; - - /** - * @category Common Helpers - * @summary Return the earliest of the given dates. - * - * @description - * Return the earliest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the earliest of the dates - * - * @example - * // Which of these dates is the earliest? - * var result = min( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Wed Feb 11 1987 00:00:00 - */ - function min () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var earliestTimestamp = Math.min.apply(null, dates); - return new Date(earliestTimestamp) - } - - var min_1 = min; - - /** - * @category Day Helpers - * @summary Set the day of the month to the given date. - * - * @description - * Set the day of the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfMonth - the day of the month of the new date - * @returns {Date} the new date with the day of the month setted - * - * @example - * // Set the 30th day of the month to 1 September 2014: - * var result = setDate(new Date(2014, 8, 1), 30) - * //=> Tue Sep 30 2014 00:00:00 - */ - function setDate (dirtyDate, dirtyDayOfMonth) { - var date = parse_1(dirtyDate); - var dayOfMonth = Number(dirtyDayOfMonth); - date.setDate(dayOfMonth); - return date - } - - var set_date = setDate; - - /** - * @category Weekday Helpers - * @summary Set the day of the week to the given date. - * - * @description - * Set the day of the week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the week of the new date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the new date with the day of the week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If week starts with Monday, set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0, {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ - function setDay (dirtyDate, dirtyDay, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = date.getDay(); - - var remainder = day % 7; - var dayIndex = (remainder + 7) % 7; - - var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; - return add_days(date, diff) - } - - var set_day = setDay; - - /** - * @category Day Helpers - * @summary Set the day of the year to the given date. - * - * @description - * Set the day of the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfYear - the day of the year of the new date - * @returns {Date} the new date with the day of the year setted - * - * @example - * // Set the 2nd day of the year to 2 July 2014: - * var result = setDayOfYear(new Date(2014, 6, 2), 2) - * //=> Thu Jan 02 2014 00:00:00 - */ - function setDayOfYear (dirtyDate, dirtyDayOfYear) { - var date = parse_1(dirtyDate); - var dayOfYear = Number(dirtyDayOfYear); - date.setMonth(0); - date.setDate(dayOfYear); - return date - } - - var set_day_of_year = setDayOfYear; - - /** - * @category Hour Helpers - * @summary Set the hours to the given date. - * - * @description - * Set the hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} hours - the hours of the new date - * @returns {Date} the new date with the hours setted - * - * @example - * // Set 4 hours to 1 September 2014 11:30:00: - * var result = setHours(new Date(2014, 8, 1, 11, 30), 4) - * //=> Mon Sep 01 2014 04:30:00 - */ - function setHours (dirtyDate, dirtyHours) { - var date = parse_1(dirtyDate); - var hours = Number(dirtyHours); - date.setHours(hours); - return date - } - - var set_hours = setHours; - - /** - * @category Weekday Helpers - * @summary Set the day of the ISO week to the given date. - * - * @description - * Set the day of the ISO week to the given date. - * ISO week starts with Monday. - * 7 is the index of Sunday, 1 is the index of Monday etc. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the ISO week of the new date - * @returns {Date} the new date with the day of the ISO week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setISODay(new Date(2014, 8, 1), 7) - * //=> Sun Sep 07 2014 00:00:00 - */ - function setISODay (dirtyDate, dirtyDay) { - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = get_iso_day(date); - var diff = day - currentDay; - return add_days(date, diff) - } - - var set_iso_day = setISODay; - - /** - * @category ISO Week Helpers - * @summary Set the ISO week to the given date. - * - * @description - * Set the ISO week to the given date, saving the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoWeek - the ISO week of the new date - * @returns {Date} the new date with the ISO week setted - * - * @example - * // Set the 53rd ISO week to 7 August 2004: - * var result = setISOWeek(new Date(2004, 7, 7), 53) - * //=> Sat Jan 01 2005 00:00:00 - */ - function setISOWeek (dirtyDate, dirtyISOWeek) { - var date = parse_1(dirtyDate); - var isoWeek = Number(dirtyISOWeek); - var diff = get_iso_week(date) - isoWeek; - date.setDate(date.getDate() - diff * 7); - return date - } - - var set_iso_week = setISOWeek; - - /** - * @category Millisecond Helpers - * @summary Set the milliseconds to the given date. - * - * @description - * Set the milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} milliseconds - the milliseconds of the new date - * @returns {Date} the new date with the milliseconds setted - * - * @example - * // Set 300 milliseconds to 1 September 2014 11:30:40.500: - * var result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300) - * //=> Mon Sep 01 2014 11:30:40.300 - */ - function setMilliseconds (dirtyDate, dirtyMilliseconds) { - var date = parse_1(dirtyDate); - var milliseconds = Number(dirtyMilliseconds); - date.setMilliseconds(milliseconds); - return date - } - - var set_milliseconds = setMilliseconds; - - /** - * @category Minute Helpers - * @summary Set the minutes to the given date. - * - * @description - * Set the minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} minutes - the minutes of the new date - * @returns {Date} the new date with the minutes setted - * - * @example - * // Set 45 minutes to 1 September 2014 11:30:40: - * var result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:45:40 - */ - function setMinutes (dirtyDate, dirtyMinutes) { - var date = parse_1(dirtyDate); - var minutes = Number(dirtyMinutes); - date.setMinutes(minutes); - return date - } - - var set_minutes = setMinutes; - - /** - * @category Month Helpers - * @summary Set the month to the given date. - * - * @description - * Set the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} month - the month of the new date - * @returns {Date} the new date with the month setted - * - * @example - * // Set February to 1 September 2014: - * var result = setMonth(new Date(2014, 8, 1), 1) - * //=> Sat Feb 01 2014 00:00:00 - */ - function setMonth (dirtyDate, dirtyMonth) { - var date = parse_1(dirtyDate); - var month = Number(dirtyMonth); - var year = date.getFullYear(); - var day = date.getDate(); - - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(year, month, 15); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(month, Math.min(day, daysInMonth)); - return date - } - - var set_month = setMonth; - - /** - * @category Quarter Helpers - * @summary Set the year quarter to the given date. - * - * @description - * Set the year quarter to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} quarter - the quarter of the new date - * @returns {Date} the new date with the quarter setted - * - * @example - * // Set the 2nd quarter to 2 July 2014: - * var result = setQuarter(new Date(2014, 6, 2), 2) - * //=> Wed Apr 02 2014 00:00:00 - */ - function setQuarter (dirtyDate, dirtyQuarter) { - var date = parse_1(dirtyDate); - var quarter = Number(dirtyQuarter); - var oldQuarter = Math.floor(date.getMonth() / 3) + 1; - var diff = quarter - oldQuarter; - return set_month(date, date.getMonth() + diff * 3) - } - - var set_quarter = setQuarter; - - /** - * @category Second Helpers - * @summary Set the seconds to the given date. - * - * @description - * Set the seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} seconds - the seconds of the new date - * @returns {Date} the new date with the seconds setted - * - * @example - * // Set 45 seconds to 1 September 2014 11:30:40: - * var result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:30:45 - */ - function setSeconds (dirtyDate, dirtySeconds) { - var date = parse_1(dirtyDate); - var seconds = Number(dirtySeconds); - date.setSeconds(seconds); - return date - } - - var set_seconds = setSeconds; - - /** - * @category Year Helpers - * @summary Set the year to the given date. - * - * @description - * Set the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} year - the year of the new date - * @returns {Date} the new date with the year setted - * - * @example - * // Set year 2013 to 1 September 2014: - * var result = setYear(new Date(2014, 8, 1), 2013) - * //=> Sun Sep 01 2013 00:00:00 - */ - function setYear (dirtyDate, dirtyYear) { - var date = parse_1(dirtyDate); - var year = Number(dirtyYear); - date.setFullYear(year); - return date - } - - var set_year = setYear; - - /** - * @category Month Helpers - * @summary Return the start of a month for the given date. - * - * @description - * Return the start of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a month - * - * @example - * // The start of a month for 2 September 2014 11:55:00: - * var result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - date.setDate(1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_month = startOfMonth; - - /** - * @category Day Helpers - * @summary Return the start of today. - * - * @description - * Return the start of today. - * - * @returns {Date} the start of today - * - * @example - * // If today is 6 October 2014: - * var result = startOfToday() - * //=> Mon Oct 6 2014 00:00:00 - */ - function startOfToday () { - return start_of_day(new Date()) - } - - var start_of_today = startOfToday; - - /** - * @category Day Helpers - * @summary Return the start of tomorrow. - * - * @description - * Return the start of tomorrow. - * - * @returns {Date} the start of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = startOfTomorrow() - * //=> Tue Oct 7 2014 00:00:00 - */ - function startOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_tomorrow = startOfTomorrow; - - /** - * @category Day Helpers - * @summary Return the start of yesterday. - * - * @description - * Return the start of yesterday. - * - * @returns {Date} the start of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = startOfYesterday() - * //=> Sun Oct 5 2014 00:00:00 - */ - function startOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_yesterday = startOfYesterday; - - /** - * @category Day Helpers - * @summary Subtract the specified number of days from the given date. - * - * @description - * Subtract the specified number of days from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be subtracted - * @returns {Date} the new date with the days subtracted - * - * @example - * // Subtract 10 days from 1 September 2014: - * var result = subDays(new Date(2014, 8, 1), 10) - * //=> Fri Aug 22 2014 00:00:00 - */ - function subDays (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_days(dirtyDate, -amount) - } - - var sub_days = subDays; - - /** - * @category Hour Helpers - * @summary Subtract the specified number of hours from the given date. - * - * @description - * Subtract the specified number of hours from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be subtracted - * @returns {Date} the new date with the hours subtracted - * - * @example - * // Subtract 2 hours from 11 July 2014 01:00:00: - * var result = subHours(new Date(2014, 6, 11, 1, 0), 2) - * //=> Thu Jul 10 2014 23:00:00 - */ - function subHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_hours(dirtyDate, -amount) - } - - var sub_hours = subHours; - - /** - * @category Millisecond Helpers - * @summary Subtract the specified number of milliseconds from the given date. - * - * @description - * Subtract the specified number of milliseconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be subtracted - * @returns {Date} the new date with the milliseconds subtracted - * - * @example - * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: - * var result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:29.250 - */ - function subMilliseconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, -amount) - } - - var sub_milliseconds = subMilliseconds; - - /** - * @category Minute Helpers - * @summary Subtract the specified number of minutes from the given date. - * - * @description - * Subtract the specified number of minutes from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be subtracted - * @returns {Date} the new date with the mintues subtracted - * - * @example - * // Subtract 30 minutes from 10 July 2014 12:00:00: - * var result = subMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 11:30:00 - */ - function subMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_minutes(dirtyDate, -amount) - } - - var sub_minutes = subMinutes; - - /** - * @category Month Helpers - * @summary Subtract the specified number of months from the given date. - * - * @description - * Subtract the specified number of months from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be subtracted - * @returns {Date} the new date with the months subtracted - * - * @example - * // Subtract 5 months from 1 February 2015: - * var result = subMonths(new Date(2015, 1, 1), 5) - * //=> Mon Sep 01 2014 00:00:00 - */ - function subMonths (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, -amount) - } - - var sub_months = subMonths; - - /** - * @category Quarter Helpers - * @summary Subtract the specified number of year quarters from the given date. - * - * @description - * Subtract the specified number of year quarters from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be subtracted - * @returns {Date} the new date with the quarters subtracted - * - * @example - * // Subtract 3 quarters from 1 September 2014: - * var result = subQuarters(new Date(2014, 8, 1), 3) - * //=> Sun Dec 01 2013 00:00:00 - */ - function subQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_quarters(dirtyDate, -amount) - } - - var sub_quarters = subQuarters; - - /** - * @category Second Helpers - * @summary Subtract the specified number of seconds from the given date. - * - * @description - * Subtract the specified number of seconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be subtracted - * @returns {Date} the new date with the seconds subtracted - * - * @example - * // Subtract 30 seconds from 10 July 2014 12:45:00: - * var result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:44:30 - */ - function subSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_seconds(dirtyDate, -amount) - } - - var sub_seconds = subSeconds; - - /** - * @category Week Helpers - * @summary Subtract the specified number of weeks from the given date. - * - * @description - * Subtract the specified number of weeks from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be subtracted - * @returns {Date} the new date with the weeks subtracted - * - * @example - * // Subtract 4 weeks from 1 September 2014: - * var result = subWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Aug 04 2014 00:00:00 - */ - function subWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_weeks(dirtyDate, -amount) - } - - var sub_weeks = subWeeks; - - /** - * @category Year Helpers - * @summary Subtract the specified number of years from the given date. - * - * @description - * Subtract the specified number of years from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be subtracted - * @returns {Date} the new date with the years subtracted - * - * @example - * // Subtract 5 years from 1 September 2014: - * var result = subYears(new Date(2014, 8, 1), 5) - * //=> Tue Sep 01 2009 00:00:00 - */ - function subYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_years(dirtyDate, -amount) - } - - var sub_years = subYears; - - var dateFns = { - addDays: add_days, - addHours: add_hours, - addISOYears: add_iso_years, - addMilliseconds: add_milliseconds, - addMinutes: add_minutes, - addMonths: add_months, - addQuarters: add_quarters, - addSeconds: add_seconds, - addWeeks: add_weeks, - addYears: add_years, - areRangesOverlapping: are_ranges_overlapping, - closestIndexTo: closest_index_to, - closestTo: closest_to, - compareAsc: compare_asc, - compareDesc: compare_desc, - differenceInCalendarDays: difference_in_calendar_days, - differenceInCalendarISOWeeks: difference_in_calendar_iso_weeks, - differenceInCalendarISOYears: difference_in_calendar_iso_years, - differenceInCalendarMonths: difference_in_calendar_months, - differenceInCalendarQuarters: difference_in_calendar_quarters, - differenceInCalendarWeeks: difference_in_calendar_weeks, - differenceInCalendarYears: difference_in_calendar_years, - differenceInDays: difference_in_days, - differenceInHours: difference_in_hours, - differenceInISOYears: difference_in_iso_years, - differenceInMilliseconds: difference_in_milliseconds, - differenceInMinutes: difference_in_minutes, - differenceInMonths: difference_in_months, - differenceInQuarters: difference_in_quarters, - differenceInSeconds: difference_in_seconds, - differenceInWeeks: difference_in_weeks, - differenceInYears: difference_in_years, - distanceInWords: distance_in_words, - distanceInWordsStrict: distance_in_words_strict, - distanceInWordsToNow: distance_in_words_to_now, - eachDay: each_day, - endOfDay: end_of_day, - endOfHour: end_of_hour, - endOfISOWeek: end_of_iso_week, - endOfISOYear: end_of_iso_year, - endOfMinute: end_of_minute, - endOfMonth: end_of_month, - endOfQuarter: end_of_quarter, - endOfSecond: end_of_second, - endOfToday: end_of_today, - endOfTomorrow: end_of_tomorrow, - endOfWeek: end_of_week, - endOfYear: end_of_year, - endOfYesterday: end_of_yesterday, - format: format_1, - getDate: get_date, - getDay: get_day, - getDayOfYear: get_day_of_year, - getDaysInMonth: get_days_in_month, - getDaysInYear: get_days_in_year, - getHours: get_hours, - getISODay: get_iso_day, - getISOWeek: get_iso_week, - getISOWeeksInYear: get_iso_weeks_in_year, - getISOYear: get_iso_year, - getMilliseconds: get_milliseconds, - getMinutes: get_minutes, - getMonth: get_month, - getOverlappingDaysInRanges: get_overlapping_days_in_ranges, - getQuarter: get_quarter, - getSeconds: get_seconds, - getTime: get_time, - getYear: get_year, - isAfter: is_after, - isBefore: is_before, - isDate: is_date, - isEqual: is_equal, - isFirstDayOfMonth: is_first_day_of_month, - isFriday: is_friday, - isFuture: is_future, - isLastDayOfMonth: is_last_day_of_month, - isLeapYear: is_leap_year, - isMonday: is_monday, - isPast: is_past, - isSameDay: is_same_day, - isSameHour: is_same_hour, - isSameISOWeek: is_same_iso_week, - isSameISOYear: is_same_iso_year, - isSameMinute: is_same_minute, - isSameMonth: is_same_month, - isSameQuarter: is_same_quarter, - isSameSecond: is_same_second, - isSameWeek: is_same_week, - isSameYear: is_same_year, - isSaturday: is_saturday, - isSunday: is_sunday, - isThisHour: is_this_hour, - isThisISOWeek: is_this_iso_week, - isThisISOYear: is_this_iso_year, - isThisMinute: is_this_minute, - isThisMonth: is_this_month, - isThisQuarter: is_this_quarter, - isThisSecond: is_this_second, - isThisWeek: is_this_week, - isThisYear: is_this_year, - isThursday: is_thursday, - isToday: is_today, - isTomorrow: is_tomorrow, - isTuesday: is_tuesday, - isValid: is_valid, - isWednesday: is_wednesday, - isWeekend: is_weekend, - isWithinRange: is_within_range, - isYesterday: is_yesterday, - lastDayOfISOWeek: last_day_of_iso_week, - lastDayOfISOYear: last_day_of_iso_year, - lastDayOfMonth: last_day_of_month, - lastDayOfQuarter: last_day_of_quarter, - lastDayOfWeek: last_day_of_week, - lastDayOfYear: last_day_of_year, - max: max_1, - min: min_1, - parse: parse_1, - setDate: set_date, - setDay: set_day, - setDayOfYear: set_day_of_year, - setHours: set_hours, - setISODay: set_iso_day, - setISOWeek: set_iso_week, - setISOYear: set_iso_year, - setMilliseconds: set_milliseconds, - setMinutes: set_minutes, - setMonth: set_month, - setQuarter: set_quarter, - setSeconds: set_seconds, - setYear: set_year, - startOfDay: start_of_day, - startOfHour: start_of_hour, - startOfISOWeek: start_of_iso_week, - startOfISOYear: start_of_iso_year, - startOfMinute: start_of_minute, - startOfMonth: start_of_month, - startOfQuarter: start_of_quarter, - startOfSecond: start_of_second, - startOfToday: start_of_today, - startOfTomorrow: start_of_tomorrow, - startOfWeek: start_of_week, - startOfYear: start_of_year, - startOfYesterday: start_of_yesterday, - subDays: sub_days, - subHours: sub_hours, - subISOYears: sub_iso_years, - subMilliseconds: sub_milliseconds, - subMinutes: sub_minutes, - subMonths: sub_months, - subQuarters: sub_quarters, - subSeconds: sub_seconds, - subWeeks: sub_weeks, - subYears: sub_years - }; - - const user = "user"; - - const date$2 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo$2 = `Sunnyvale ${user} ${date$2}`; - - const date$1 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo$1 = `@foo/lib/a ${date$1}`; - - const date = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo = `@foo/lib/a/a/a ${date}`; - - const fum = 'Wonderland'; - - var hello = 'Hello'; - - const name = 'Alice'; - - const json_key = "json_value"; - - console.log( - `${hello}, ${name} in ${fum} ${foo$2} ${foo$1} ${foo} ${far_a} ${far_a_b_c} ${json_key}`); - - // Test for sequences = false - class A { - a() { - return document.a; - } - } - function inline_me() { - return 'abc'; - } - console.error(new A().a(), inline_me(), some_global_var.thing); - - exports.A = A; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}); -//# sourceMappingURL=bundle.amd.js.map
diff --git a/packages/rollup/test/integration/golden.cjs.js.map.sha256_ b/packages/rollup/test/integration/golden.cjs.js.map.sha256_ deleted file mode 100644 index 4a1b5a1..0000000 --- a/packages/rollup/test/integration/golden.cjs.js.map.sha256_ +++ /dev/null
@@ -1 +0,0 @@ -7968687ed52c81d2622e22e914927b8acacf641b10097bdf7ca2dedbbc361f26 \ No newline at end of file
diff --git a/packages/rollup/test/integration/golden.cjs.js_ b/packages/rollup/test/integration/golden.cjs.js_ deleted file mode 100644 index ed017ef..0000000 --- a/packages/rollup/test/integration/golden.cjs.js_ +++ /dev/null
@@ -1,5682 +0,0 @@ -/** - * @license A dummy license banner that goes at the top of the file. - * This is version <unknown> - */ - -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -var some_global_var = require('some_global_var'); - -var far_a = `@far/a`; - -var far_a_b_c = `@far/a/b/c`; - -var MILLISECONDS_IN_MINUTE$6 = 60000; - -/** - * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. - * They usually appear for dates that denote time before the timezones were introduced - * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 - * and GMT+01:00:00 after that date) - * - * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above, - * which would lead to incorrect calculations. - * - * This function returns the timezone offset in milliseconds that takes seconds in account. - */ -var getTimezoneOffsetInMilliseconds = function getTimezoneOffsetInMilliseconds (dirtyDate) { - var date = new Date(dirtyDate.getTime()); - var baseTimezoneOffset = date.getTimezoneOffset(); - date.setSeconds(0, 0); - var millisecondsPartOfTimezoneOffset = date.getTime() % MILLISECONDS_IN_MINUTE$6; - - return baseTimezoneOffset * MILLISECONDS_IN_MINUTE$6 + millisecondsPartOfTimezoneOffset -}; - -/** - * @category Common Helpers - * @summary Is the given argument an instance of Date? - * - * @description - * Is the given argument an instance of Date? - * - * @param {*} argument - the argument to check - * @returns {Boolean} the given argument is an instance of Date - * - * @example - * // Is 'mayonnaise' a Date? - * var result = isDate('mayonnaise') - * //=> false - */ -function isDate (argument) { - return argument instanceof Date -} - -var is_date = isDate; - -var MILLISECONDS_IN_HOUR$2 = 3600000; -var MILLISECONDS_IN_MINUTE$5 = 60000; -var DEFAULT_ADDITIONAL_DIGITS = 2; - -var parseTokenDateTimeDelimeter = /[T ]/; -var parseTokenPlainTime = /:/; - -// year tokens -var parseTokenYY = /^(\d{2})$/; -var parseTokensYYY = [ - /^([+-]\d{2})$/, // 0 additional digits - /^([+-]\d{3})$/, // 1 additional digit - /^([+-]\d{4})$/ // 2 additional digits -]; - -var parseTokenYYYY = /^(\d{4})/; -var parseTokensYYYYY = [ - /^([+-]\d{4})/, // 0 additional digits - /^([+-]\d{5})/, // 1 additional digit - /^([+-]\d{6})/ // 2 additional digits -]; - -// date tokens -var parseTokenMM = /^-(\d{2})$/; -var parseTokenDDD = /^-?(\d{3})$/; -var parseTokenMMDD = /^-?(\d{2})-?(\d{2})$/; -var parseTokenWww = /^-?W(\d{2})$/; -var parseTokenWwwD = /^-?W(\d{2})-?(\d{1})$/; - -// time tokens -var parseTokenHH = /^(\d{2}([.,]\d*)?)$/; -var parseTokenHHMM = /^(\d{2}):?(\d{2}([.,]\d*)?)$/; -var parseTokenHHMMSS = /^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/; - -// timezone tokens -var parseTokenTimezone = /([Z+-].*)$/; -var parseTokenTimezoneZ = /^(Z)$/; -var parseTokenTimezoneHH = /^([+-])(\d{2})$/; -var parseTokenTimezoneHHMM = /^([+-])(\d{2}):?(\d{2})$/; - -/** - * @category Common Helpers - * @summary Convert the given argument to an instance of Date. - * - * @description - * Convert the given argument to an instance of Date. - * - * If the argument is an instance of Date, the function returns its clone. - * - * If the argument is a number, it is treated as a timestamp. - * - * If an argument is a string, the function tries to parse it. - * Function accepts complete ISO 8601 formats as well as partial implementations. - * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 - * - * If all above fails, the function passes the given argument to Date constructor. - * - * @param {Date|String|Number} argument - the value to convert - * @param {Object} [options] - the object with options - * @param {0 | 1 | 2} [options.additionalDigits=2] - the additional number of digits in the extended year format - * @returns {Date} the parsed date in the local time zone - * - * @example - * // Convert string '2014-02-11T11:30:30' to date: - * var result = parse('2014-02-11T11:30:30') - * //=> Tue Feb 11 2014 11:30:30 - * - * @example - * // Parse string '+02014101', - * // if the additional number of digits in the extended year format is 1: - * var result = parse('+02014101', {additionalDigits: 1}) - * //=> Fri Apr 11 2014 00:00:00 - */ -function parse (argument, dirtyOptions) { - if (is_date(argument)) { - // Prevent the date to lose the milliseconds when passed to new Date() in IE10 - return new Date(argument.getTime()) - } else if (typeof argument !== 'string') { - return new Date(argument) - } - - var options = dirtyOptions || {}; - var additionalDigits = options.additionalDigits; - if (additionalDigits == null) { - additionalDigits = DEFAULT_ADDITIONAL_DIGITS; - } else { - additionalDigits = Number(additionalDigits); - } - - var dateStrings = splitDateString(argument); - - var parseYearResult = parseYear(dateStrings.date, additionalDigits); - var year = parseYearResult.year; - var restDateString = parseYearResult.restDateString; - - var date = parseDate(restDateString, year); - - if (date) { - var timestamp = date.getTime(); - var time = 0; - var offset; - - if (dateStrings.time) { - time = parseTime(dateStrings.time); - } - - if (dateStrings.timezone) { - offset = parseTimezone(dateStrings.timezone) * MILLISECONDS_IN_MINUTE$5; - } else { - var fullTime = timestamp + time; - var fullTimeDate = new Date(fullTime); - - offset = getTimezoneOffsetInMilliseconds(fullTimeDate); - - // Adjust time when it's coming from DST - var fullTimeDateNextDay = new Date(fullTime); - fullTimeDateNextDay.setDate(fullTimeDate.getDate() + 1); - var offsetDiff = - getTimezoneOffsetInMilliseconds(fullTimeDateNextDay) - - getTimezoneOffsetInMilliseconds(fullTimeDate); - if (offsetDiff > 0) { - offset += offsetDiff; - } - } - - return new Date(timestamp + time + offset) - } else { - return new Date(argument) - } -} - -function splitDateString (dateString) { - var dateStrings = {}; - var array = dateString.split(parseTokenDateTimeDelimeter); - var timeString; - - if (parseTokenPlainTime.test(array[0])) { - dateStrings.date = null; - timeString = array[0]; - } else { - dateStrings.date = array[0]; - timeString = array[1]; - } - - if (timeString) { - var token = parseTokenTimezone.exec(timeString); - if (token) { - dateStrings.time = timeString.replace(token[1], ''); - dateStrings.timezone = token[1]; - } else { - dateStrings.time = timeString; - } - } - - return dateStrings -} - -function parseYear (dateString, additionalDigits) { - var parseTokenYYY = parseTokensYYY[additionalDigits]; - var parseTokenYYYYY = parseTokensYYYYY[additionalDigits]; - - var token; - - // YYYY or ±YYYYY - token = parseTokenYYYY.exec(dateString) || parseTokenYYYYY.exec(dateString); - if (token) { - var yearString = token[1]; - return { - year: parseInt(yearString, 10), - restDateString: dateString.slice(yearString.length) - } - } - - // YY or ±YYY - token = parseTokenYY.exec(dateString) || parseTokenYYY.exec(dateString); - if (token) { - var centuryString = token[1]; - return { - year: parseInt(centuryString, 10) * 100, - restDateString: dateString.slice(centuryString.length) - } - } - - // Invalid ISO-formatted year - return { - year: null - } -} - -function parseDate (dateString, year) { - // Invalid ISO-formatted year - if (year === null) { - return null - } - - var token; - var date; - var month; - var week; - - // YYYY - if (dateString.length === 0) { - date = new Date(0); - date.setUTCFullYear(year); - return date - } - - // YYYY-MM - token = parseTokenMM.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - date.setUTCFullYear(year, month); - return date - } - - // YYYY-DDD or YYYYDDD - token = parseTokenDDD.exec(dateString); - if (token) { - date = new Date(0); - var dayOfYear = parseInt(token[1], 10); - date.setUTCFullYear(year, 0, dayOfYear); - return date - } - - // YYYY-MM-DD or YYYYMMDD - token = parseTokenMMDD.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - var day = parseInt(token[2], 10); - date.setUTCFullYear(year, month, day); - return date - } - - // YYYY-Www or YYYYWww - token = parseTokenWww.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - return dayOfISOYear(year, week) - } - - // YYYY-Www-D or YYYYWwwD - token = parseTokenWwwD.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - var dayOfWeek = parseInt(token[2], 10) - 1; - return dayOfISOYear(year, week, dayOfWeek) - } - - // Invalid ISO-formatted date - return null -} - -function parseTime (timeString) { - var token; - var hours; - var minutes; - - // hh - token = parseTokenHH.exec(timeString); - if (token) { - hours = parseFloat(token[1].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 - } - - // hh:mm or hhmm - token = parseTokenHHMM.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseFloat(token[2].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 - } - - // hh:mm:ss or hhmmss - token = parseTokenHHMMSS.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseInt(token[2], 10); - var seconds = parseFloat(token[3].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 + - seconds * 1000 - } - - // Invalid ISO-formatted time - return null -} - -function parseTimezone (timezoneString) { - var token; - var absoluteOffset; - - // Z - token = parseTokenTimezoneZ.exec(timezoneString); - if (token) { - return 0 - } - - // ±hh - token = parseTokenTimezoneHH.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60; - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - // ±hh:mm or ±hhmm - token = parseTokenTimezoneHHMM.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60 + parseInt(token[3], 10); - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - return 0 -} - -function dayOfISOYear (isoYear, week, day) { - week = week || 0; - day = day || 0; - var date = new Date(0); - date.setUTCFullYear(isoYear, 0, 4); - var fourthOfJanuaryDay = date.getUTCDay() || 7; - var diff = week * 7 + day + 1 - fourthOfJanuaryDay; - date.setUTCDate(date.getUTCDate() + diff); - return date -} - -var parse_1 = parse; - -/** - * @category Day Helpers - * @summary Add the specified number of days to the given date. - * - * @description - * Add the specified number of days to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be added - * @returns {Date} the new date with the days added - * - * @example - * // Add 10 days to 1 September 2014: - * var result = addDays(new Date(2014, 8, 1), 10) - * //=> Thu Sep 11 2014 00:00:00 - */ -function addDays (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - date.setDate(date.getDate() + amount); - return date -} - -var add_days = addDays; - -/** - * @category Millisecond Helpers - * @summary Add the specified number of milliseconds to the given date. - * - * @description - * Add the specified number of milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be added - * @returns {Date} the new date with the milliseconds added - * - * @example - * // Add 750 milliseconds to 10 July 2014 12:45:30.000: - * var result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:30.750 - */ -function addMilliseconds (dirtyDate, dirtyAmount) { - var timestamp = parse_1(dirtyDate).getTime(); - var amount = Number(dirtyAmount); - return new Date(timestamp + amount) -} - -var add_milliseconds = addMilliseconds; - -var MILLISECONDS_IN_HOUR$1 = 3600000; - -/** - * @category Hour Helpers - * @summary Add the specified number of hours to the given date. - * - * @description - * Add the specified number of hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be added - * @returns {Date} the new date with the hours added - * - * @example - * // Add 2 hours to 10 July 2014 23:00:00: - * var result = addHours(new Date(2014, 6, 10, 23, 0), 2) - * //=> Fri Jul 11 2014 01:00:00 - */ -function addHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR$1) -} - -var add_hours = addHours; - -/** - * @category Week Helpers - * @summary Return the start of a week for the given date. - * - * @description - * Return the start of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the start of a week - * - * @example - * // The start of a week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Mon Sep 01 2014 00:00:00 - */ -function startOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - - date.setDate(date.getDate() - diff); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_week = startOfWeek; - -/** - * @category ISO Week Helpers - * @summary Return the start of an ISO week for the given date. - * - * @description - * Return the start of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO week - * - * @example - * // The start of an ISO week for 2 September 2014 11:55:00: - * var result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ -function startOfISOWeek (dirtyDate) { - return start_of_week(dirtyDate, {weekStartsOn: 1}) -} - -var start_of_iso_week = startOfISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Get the ISO week-numbering year of the given date. - * - * @description - * Get the ISO week-numbering year of the given date, - * which always starts 3 days before the year's first Thursday. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week-numbering year - * - * @example - * // Which ISO-week numbering year is 2 January 2005? - * var result = getISOYear(new Date(2005, 0, 2)) - * //=> 2004 - */ -function getISOYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var startOfNextYear = start_of_iso_week(fourthOfJanuaryOfNextYear); - - var fourthOfJanuaryOfThisYear = new Date(0); - fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); - fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); - var startOfThisYear = start_of_iso_week(fourthOfJanuaryOfThisYear); - - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1 - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year - } else { - return year - 1 - } -} - -var get_iso_year = getISOYear; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Return the start of an ISO week-numbering year for the given date. - * - * @description - * Return the start of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO year - * - * @example - * // The start of an ISO week-numbering year for 2 July 2005: - * var result = startOfISOYear(new Date(2005, 6, 2)) - * //=> Mon Jan 03 2005 00:00:00 - */ -function startOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - return date -} - -var start_of_iso_year = startOfISOYear; - -/** - * @category Day Helpers - * @summary Return the start of a day for the given date. - * - * @description - * Return the start of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a day - * - * @example - * // The start of a day for 2 September 2014 11:55:00: - * var result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 00:00:00 - */ -function startOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_day = startOfDay; - -var MILLISECONDS_IN_MINUTE$4 = 60000; -var MILLISECONDS_IN_DAY$1 = 86400000; - -/** - * @category Day Helpers - * @summary Get the number of calendar days between the given dates. - * - * @description - * Get the number of calendar days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar days - * - * @example - * // How many calendar days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInCalendarDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 366 - */ -function differenceInCalendarDays (dirtyDateLeft, dirtyDateRight) { - var startOfDayLeft = start_of_day(dirtyDateLeft); - var startOfDayRight = start_of_day(dirtyDateRight); - - var timestampLeft = startOfDayLeft.getTime() - - startOfDayLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - var timestampRight = startOfDayRight.getTime() - - startOfDayRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a day is not constant - // (e.g. it's different in the day of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY$1) -} - -var difference_in_calendar_days = differenceInCalendarDays; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Set the ISO week-numbering year to the given date. - * - * @description - * Set the ISO week-numbering year to the given date, - * saving the week number and the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoYear - the ISO week-numbering year of the new date - * @returns {Date} the new date with the ISO week-numbering year setted - * - * @example - * // Set ISO week-numbering year 2007 to 29 December 2008: - * var result = setISOYear(new Date(2008, 11, 29), 2007) - * //=> Mon Jan 01 2007 00:00:00 - */ -function setISOYear (dirtyDate, dirtyISOYear) { - var date = parse_1(dirtyDate); - var isoYear = Number(dirtyISOYear); - var diff = difference_in_calendar_days(date, start_of_iso_year(date)); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(isoYear, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - date = start_of_iso_year(fourthOfJanuary); - date.setDate(date.getDate() + diff); - return date -} - -var set_iso_year = setISOYear; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Add the specified number of ISO week-numbering years to the given date. - * - * @description - * Add the specified number of ISO week-numbering years to the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be added - * @returns {Date} the new date with the ISO week-numbering years added - * - * @example - * // Add 5 ISO week-numbering years to 2 July 2010: - * var result = addISOYears(new Date(2010, 6, 2), 5) - * //=> Fri Jun 26 2015 00:00:00 - */ -function addISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return set_iso_year(dirtyDate, get_iso_year(dirtyDate) + amount) -} - -var add_iso_years = addISOYears; - -var MILLISECONDS_IN_MINUTE$3 = 60000; - -/** - * @category Minute Helpers - * @summary Add the specified number of minutes to the given date. - * - * @description - * Add the specified number of minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be added - * @returns {Date} the new date with the minutes added - * - * @example - * // Add 30 minutes to 10 July 2014 12:00:00: - * var result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 12:30:00 - */ -function addMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE$3) -} - -var add_minutes = addMinutes; - -/** - * @category Month Helpers - * @summary Get the number of days in a month of the given date. - * - * @description - * Get the number of days in a month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a month - * - * @example - * // How many days are in February 2000? - * var result = getDaysInMonth(new Date(2000, 1)) - * //=> 29 - */ -function getDaysInMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - var monthIndex = date.getMonth(); - var lastDayOfMonth = new Date(0); - lastDayOfMonth.setFullYear(year, monthIndex + 1, 0); - lastDayOfMonth.setHours(0, 0, 0, 0); - return lastDayOfMonth.getDate() -} - -var get_days_in_month = getDaysInMonth; - -/** - * @category Month Helpers - * @summary Add the specified number of months to the given date. - * - * @description - * Add the specified number of months to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be added - * @returns {Date} the new date with the months added - * - * @example - * // Add 5 months to 1 September 2014: - * var result = addMonths(new Date(2014, 8, 1), 5) - * //=> Sun Feb 01 2015 00:00:00 - */ -function addMonths (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - var desiredMonth = date.getMonth() + amount; - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(date.getFullYear(), desiredMonth, 1); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(desiredMonth, Math.min(daysInMonth, date.getDate())); - return date -} - -var add_months = addMonths; - -/** - * @category Quarter Helpers - * @summary Add the specified number of year quarters to the given date. - * - * @description - * Add the specified number of year quarters to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be added - * @returns {Date} the new date with the quarters added - * - * @example - * // Add 1 quarter to 1 September 2014: - * var result = addQuarters(new Date(2014, 8, 1), 1) - * //=> Mon Dec 01 2014 00:00:00 - */ -function addQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var months = amount * 3; - return add_months(dirtyDate, months) -} - -var add_quarters = addQuarters; - -/** - * @category Second Helpers - * @summary Add the specified number of seconds to the given date. - * - * @description - * Add the specified number of seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be added - * @returns {Date} the new date with the seconds added - * - * @example - * // Add 30 seconds to 10 July 2014 12:45:00: - * var result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:45:30 - */ -function addSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * 1000) -} - -var add_seconds = addSeconds; - -/** - * @category Week Helpers - * @summary Add the specified number of weeks to the given date. - * - * @description - * Add the specified number of week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be added - * @returns {Date} the new date with the weeks added - * - * @example - * // Add 4 weeks to 1 September 2014: - * var result = addWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Sep 29 2014 00:00:00 - */ -function addWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var days = amount * 7; - return add_days(dirtyDate, days) -} - -var add_weeks = addWeeks; - -/** - * @category Year Helpers - * @summary Add the specified number of years to the given date. - * - * @description - * Add the specified number of years to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be added - * @returns {Date} the new date with the years added - * - * @example - * // Add 5 years to 1 September 2014: - * var result = addYears(new Date(2014, 8, 1), 5) - * //=> Sun Sep 01 2019 00:00:00 - */ -function addYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, amount * 12) -} - -var add_years = addYears; - -/** - * @category Range Helpers - * @summary Is the given date range overlapping with another date range? - * - * @description - * Is the given date range overlapping with another date range? - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Boolean} whether the date ranges are overlapping - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> true - * - * @example - * // For non-overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> false - */ -function areRangesOverlapping (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return initialStartTime < comparedEndTime && comparedStartTime < initialEndTime -} - -var are_ranges_overlapping = areRangesOverlapping; - -/** - * @category Common Helpers - * @summary Return an index of the closest date from the array comparing to the given date. - * - * @description - * Return an index of the closest date from the array comparing to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Number} an index of the date closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015? - * var dateToCompare = new Date(2015, 8, 6) - * var datesArray = [ - * new Date(2015, 0, 1), - * new Date(2016, 0, 1), - * new Date(2017, 0, 1) - * ] - * var result = closestIndexTo(dateToCompare, datesArray) - * //=> 1 - */ -function closestIndexTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate, index) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = index; - minDistance = distance; - } - }); - - return result -} - -var closest_index_to = closestIndexTo; - -/** - * @category Common Helpers - * @summary Return a date from the array closest to the given date. - * - * @description - * Return a date from the array closest to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Date} the date from the array closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030? - * var dateToCompare = new Date(2015, 8, 6) - * var result = closestTo(dateToCompare, [ - * new Date(2000, 0, 1), - * new Date(2030, 0, 1) - * ]) - * //=> Tue Jan 01 2030 00:00:00 - */ -function closestTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = currentDate; - minDistance = distance; - } - }); - - return result -} - -var closest_to = closestTo; - -/** - * @category Common Helpers - * @summary Compare the two dates and return -1, 0 or 1. - * - * @description - * Compare the two dates and return 1 if the first date is after the second, - * -1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989: - * var result = compareAsc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> -1 - * - * @example - * // Sort the array of dates: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareAsc) - * //=> [ - * // Wed Feb 11 1987 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Sun Jul 02 1995 00:00:00 - * // ] - */ -function compareAsc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft < timeRight) { - return -1 - } else if (timeLeft > timeRight) { - return 1 - } else { - return 0 - } -} - -var compare_asc = compareAsc; - -/** - * @category Common Helpers - * @summary Compare the two dates reverse chronologically and return -1, 0 or 1. - * - * @description - * Compare the two dates and return -1 if the first date is after the second, - * 1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989 reverse chronologically: - * var result = compareDesc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> 1 - * - * @example - * // Sort the array of dates in reverse chronological order: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareDesc) - * //=> [ - * // Sun Jul 02 1995 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Wed Feb 11 1987 00:00:00 - * // ] - */ -function compareDesc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft > timeRight) { - return -1 - } else if (timeLeft < timeRight) { - return 1 - } else { - return 0 - } -} - -var compare_desc = compareDesc; - -var MILLISECONDS_IN_MINUTE$2 = 60000; -var MILLISECONDS_IN_WEEK$3 = 604800000; - -/** - * @category ISO Week Helpers - * @summary Get the number of calendar ISO weeks between the given dates. - * - * @description - * Get the number of calendar ISO weeks between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO weeks - * - * @example - * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014? - * var result = differenceInCalendarISOWeeks( - * new Date(2014, 6, 21), - * new Date(2014, 6, 6) - * ) - * //=> 3 - */ -function differenceInCalendarISOWeeks (dirtyDateLeft, dirtyDateRight) { - var startOfISOWeekLeft = start_of_iso_week(dirtyDateLeft); - var startOfISOWeekRight = start_of_iso_week(dirtyDateRight); - - var timestampLeft = startOfISOWeekLeft.getTime() - - startOfISOWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - var timestampRight = startOfISOWeekRight.getTime() - - startOfISOWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$3) -} - -var difference_in_calendar_iso_weeks = differenceInCalendarISOWeeks; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of calendar ISO week-numbering years between the given dates. - * - * @description - * Get the number of calendar ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO week-numbering years - * - * @example - * // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012? - * var result = differenceInCalendarISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 2 - */ -function differenceInCalendarISOYears (dirtyDateLeft, dirtyDateRight) { - return get_iso_year(dirtyDateLeft) - get_iso_year(dirtyDateRight) -} - -var difference_in_calendar_iso_years = differenceInCalendarISOYears; - -/** - * @category Month Helpers - * @summary Get the number of calendar months between the given dates. - * - * @description - * Get the number of calendar months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar months - * - * @example - * // How many calendar months are between 31 January 2014 and 1 September 2014? - * var result = differenceInCalendarMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 8 - */ -function differenceInCalendarMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); - - return yearDiff * 12 + monthDiff -} - -var difference_in_calendar_months = differenceInCalendarMonths; - -/** - * @category Quarter Helpers - * @summary Get the year quarter of the given date. - * - * @description - * Get the year quarter of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the quarter - * - * @example - * // Which quarter is 2 July 2014? - * var result = getQuarter(new Date(2014, 6, 2)) - * //=> 3 - */ -function getQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var quarter = Math.floor(date.getMonth() / 3) + 1; - return quarter -} - -var get_quarter = getQuarter; - -/** - * @category Quarter Helpers - * @summary Get the number of calendar quarters between the given dates. - * - * @description - * Get the number of calendar quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar quarters - * - * @example - * // How many calendar quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInCalendarQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 3 - */ -function differenceInCalendarQuarters (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var quarterDiff = get_quarter(dateLeft) - get_quarter(dateRight); - - return yearDiff * 4 + quarterDiff -} - -var difference_in_calendar_quarters = differenceInCalendarQuarters; - -var MILLISECONDS_IN_MINUTE$1 = 60000; -var MILLISECONDS_IN_WEEK$2 = 604800000; - -/** - * @category Week Helpers - * @summary Get the number of calendar weeks between the given dates. - * - * @description - * Get the number of calendar weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Number} the number of calendar weeks - * - * @example - * // How many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 3 - * - * @example - * // If the week starts on Monday, - * // how many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5), - * {weekStartsOn: 1} - * ) - * //=> 2 - */ -function differenceInCalendarWeeks (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var startOfWeekLeft = start_of_week(dirtyDateLeft, dirtyOptions); - var startOfWeekRight = start_of_week(dirtyDateRight, dirtyOptions); - - var timestampLeft = startOfWeekLeft.getTime() - - startOfWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - var timestampRight = startOfWeekRight.getTime() - - startOfWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$2) -} - -var difference_in_calendar_weeks = differenceInCalendarWeeks; - -/** - * @category Year Helpers - * @summary Get the number of calendar years between the given dates. - * - * @description - * Get the number of calendar years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar years - * - * @example - * // How many calendar years are between 31 December 2013 and 11 February 2015? - * var result = differenceInCalendarYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ -function differenceInCalendarYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - return dateLeft.getFullYear() - dateRight.getFullYear() -} - -var difference_in_calendar_years = differenceInCalendarYears; - -/** - * @category Day Helpers - * @summary Get the number of full days between the given dates. - * - * @description - * Get the number of full days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full days - * - * @example - * // How many full days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 365 - */ -function differenceInDays (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_days(dateLeft, dateRight)); - dateLeft.setDate(dateLeft.getDate() - sign * difference); - - // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full - // If so, result must be decreased by 1 in absolute value - var isLastDayNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastDayNotFull) -} - -var difference_in_days = differenceInDays; - -/** - * @category Millisecond Helpers - * @summary Get the number of milliseconds between the given dates. - * - * @description - * Get the number of milliseconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of milliseconds - * - * @example - * // How many milliseconds are between - * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700? - * var result = differenceInMilliseconds( - * new Date(2014, 6, 2, 12, 30, 21, 700), - * new Date(2014, 6, 2, 12, 30, 20, 600) - * ) - * //=> 1100 - */ -function differenceInMilliseconds (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getTime() - dateRight.getTime() -} - -var difference_in_milliseconds = differenceInMilliseconds; - -var MILLISECONDS_IN_HOUR = 3600000; - -/** - * @category Hour Helpers - * @summary Get the number of hours between the given dates. - * - * @description - * Get the number of hours between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of hours - * - * @example - * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00? - * var result = differenceInHours( - * new Date(2014, 6, 2, 19, 0), - * new Date(2014, 6, 2, 6, 50) - * ) - * //=> 12 - */ -function differenceInHours (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_hours = differenceInHours; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Subtract the specified number of ISO week-numbering years from the given date. - * - * @description - * Subtract the specified number of ISO week-numbering years from the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be subtracted - * @returns {Date} the new date with the ISO week-numbering years subtracted - * - * @example - * // Subtract 5 ISO week-numbering years from 1 September 2014: - * var result = subISOYears(new Date(2014, 8, 1), 5) - * //=> Mon Aug 31 2009 00:00:00 - */ -function subISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_iso_years(dirtyDate, -amount) -} - -var sub_iso_years = subISOYears; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of full ISO week-numbering years between the given dates. - * - * @description - * Get the number of full ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full ISO week-numbering years - * - * @example - * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012? - * var result = differenceInISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 1 - */ -function differenceInISOYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_iso_years(dateLeft, dateRight)); - dateLeft = sub_iso_years(dateLeft, sign * difference); - - // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1 - // if last calendar ISO year is not full - // If so, result must be decreased by 1 in absolute value - var isLastISOYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastISOYearNotFull) -} - -var difference_in_iso_years = differenceInISOYears; - -var MILLISECONDS_IN_MINUTE = 60000; - -/** - * @category Minute Helpers - * @summary Get the number of minutes between the given dates. - * - * @description - * Get the number of minutes between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of minutes - * - * @example - * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00? - * var result = differenceInMinutes( - * new Date(2014, 6, 2, 12, 20, 0), - * new Date(2014, 6, 2, 12, 7, 59) - * ) - * //=> 12 - */ -function differenceInMinutes (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_minutes = differenceInMinutes; - -/** - * @category Month Helpers - * @summary Get the number of full months between the given dates. - * - * @description - * Get the number of full months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full months - * - * @example - * // How many full months are between 31 January 2014 and 1 September 2014? - * var result = differenceInMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 7 - */ -function differenceInMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_months(dateLeft, dateRight)); - dateLeft.setMonth(dateLeft.getMonth() - sign * difference); - - // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full - // If so, result must be decreased by 1 in absolute value - var isLastMonthNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastMonthNotFull) -} - -var difference_in_months = differenceInMonths; - -/** - * @category Quarter Helpers - * @summary Get the number of full quarters between the given dates. - * - * @description - * Get the number of full quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full quarters - * - * @example - * // How many full quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ -function differenceInQuarters (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_months(dirtyDateLeft, dirtyDateRight) / 3; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_quarters = differenceInQuarters; - -/** - * @category Second Helpers - * @summary Get the number of seconds between the given dates. - * - * @description - * Get the number of seconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of seconds - * - * @example - * // How many seconds are between - * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000? - * var result = differenceInSeconds( - * new Date(2014, 6, 2, 12, 30, 20, 0), - * new Date(2014, 6, 2, 12, 30, 7, 999) - * ) - * //=> 12 - */ -function differenceInSeconds (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / 1000; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_seconds = differenceInSeconds; - -/** - * @category Week Helpers - * @summary Get the number of full weeks between the given dates. - * - * @description - * Get the number of full weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full weeks - * - * @example - * // How many full weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 2 - */ -function differenceInWeeks (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_days(dirtyDateLeft, dirtyDateRight) / 7; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_weeks = differenceInWeeks; - -/** - * @category Year Helpers - * @summary Get the number of full years between the given dates. - * - * @description - * Get the number of full years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full years - * - * @example - * // How many full years are between 31 December 2013 and 11 February 2015? - * var result = differenceInYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 1 - */ -function differenceInYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_years(dateLeft, dateRight)); - dateLeft.setFullYear(dateLeft.getFullYear() - sign * difference); - - // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full - // If so, result must be decreased by 1 in absolute value - var isLastYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastYearNotFull) -} - -var difference_in_years = differenceInYears; - -function buildDistanceInWordsLocale () { - var distanceInWordsLocale = { - lessThanXSeconds: { - one: 'less than a second', - other: 'less than {{count}} seconds' - }, - - xSeconds: { - one: '1 second', - other: '{{count}} seconds' - }, - - halfAMinute: 'half a minute', - - lessThanXMinutes: { - one: 'less than a minute', - other: 'less than {{count}} minutes' - }, - - xMinutes: { - one: '1 minute', - other: '{{count}} minutes' - }, - - aboutXHours: { - one: 'about 1 hour', - other: 'about {{count}} hours' - }, - - xHours: { - one: '1 hour', - other: '{{count}} hours' - }, - - xDays: { - one: '1 day', - other: '{{count}} days' - }, - - aboutXMonths: { - one: 'about 1 month', - other: 'about {{count}} months' - }, - - xMonths: { - one: '1 month', - other: '{{count}} months' - }, - - aboutXYears: { - one: 'about 1 year', - other: 'about {{count}} years' - }, - - xYears: { - one: '1 year', - other: '{{count}} years' - }, - - overXYears: { - one: 'over 1 year', - other: 'over {{count}} years' - }, - - almostXYears: { - one: 'almost 1 year', - other: 'almost {{count}} years' - } - }; - - function localize (token, count, options) { - options = options || {}; - - var result; - if (typeof distanceInWordsLocale[token] === 'string') { - result = distanceInWordsLocale[token]; - } else if (count === 1) { - result = distanceInWordsLocale[token].one; - } else { - result = distanceInWordsLocale[token].other.replace('{{count}}', count); - } - - if (options.addSuffix) { - if (options.comparison > 0) { - return 'in ' + result - } else { - return result + ' ago' - } - } - - return result - } - - return { - localize: localize - } -} - -var build_distance_in_words_locale = buildDistanceInWordsLocale; - -var commonFormatterKeys = [ - 'M', 'MM', 'Q', 'D', 'DD', 'DDD', 'DDDD', 'd', - 'E', 'W', 'WW', 'YY', 'YYYY', 'GG', 'GGGG', - 'H', 'HH', 'h', 'hh', 'm', 'mm', - 's', 'ss', 'S', 'SS', 'SSS', - 'Z', 'ZZ', 'X', 'x' -]; - -function buildFormattingTokensRegExp (formatters) { - var formatterKeys = []; - for (var key in formatters) { - if (formatters.hasOwnProperty(key)) { - formatterKeys.push(key); - } - } - - var formattingTokens = commonFormatterKeys - .concat(formatterKeys) - .sort() - .reverse(); - var formattingTokensRegExp = new RegExp( - '(\\[[^\\[]*\\])|(\\\\)?' + '(' + formattingTokens.join('|') + '|.)', 'g' - ); - - return formattingTokensRegExp -} - -var build_formatting_tokens_reg_exp = buildFormattingTokensRegExp; - -function buildFormatLocale () { - // Note: in English, the names of days of the week and months are capitalized. - // If you are making a new locale based on this one, check if the same is true for the language you're working on. - // Generally, formatted dates should look like they are in the middle of a sentence, - // e.g. in Spanish language the weekdays and months should be in the lowercase. - var months3char = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var monthsFull = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; - var weekdays2char = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']; - var weekdays3char = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - var weekdaysFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; - var meridiemUppercase = ['AM', 'PM']; - var meridiemLowercase = ['am', 'pm']; - var meridiemFull = ['a.m.', 'p.m.']; - - var formatters = { - // Month: Jan, Feb, ..., Dec - 'MMM': function (date) { - return months3char[date.getMonth()] - }, - - // Month: January, February, ..., December - 'MMMM': function (date) { - return monthsFull[date.getMonth()] - }, - - // Day of week: Su, Mo, ..., Sa - 'dd': function (date) { - return weekdays2char[date.getDay()] - }, - - // Day of week: Sun, Mon, ..., Sat - 'ddd': function (date) { - return weekdays3char[date.getDay()] - }, - - // Day of week: Sunday, Monday, ..., Saturday - 'dddd': function (date) { - return weekdaysFull[date.getDay()] - }, - - // AM, PM - 'A': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemUppercase[1] : meridiemUppercase[0] - }, - - // am, pm - 'a': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemLowercase[1] : meridiemLowercase[0] - }, - - // a.m., p.m. - 'aa': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemFull[1] : meridiemFull[0] - } - }; - - // Generate ordinal version of formatters: M -> Mo, D -> Do, etc. - var ordinalFormatters = ['M', 'D', 'DDD', 'd', 'Q', 'W']; - ordinalFormatters.forEach(function (formatterToken) { - formatters[formatterToken + 'o'] = function (date, formatters) { - return ordinal(formatters[formatterToken](date)) - }; - }); - - return { - formatters: formatters, - formattingTokensRegExp: build_formatting_tokens_reg_exp(formatters) - } -} - -function ordinal (number) { - var rem100 = number % 100; - if (rem100 > 20 || rem100 < 10) { - switch (rem100 % 10) { - case 1: - return number + 'st' - case 2: - return number + 'nd' - case 3: - return number + 'rd' - } - } - return number + 'th' -} - -var build_format_locale = buildFormatLocale; - -/** - * @category Locales - * @summary English locale. - */ -var en = { - distanceInWords: build_distance_in_words_locale(), - format: build_format_locale() -}; - -var MINUTES_IN_DAY$1 = 1440; -var MINUTES_IN_ALMOST_TWO_DAYS = 2520; -var MINUTES_IN_MONTH$1 = 43200; -var MINUTES_IN_TWO_MONTHS = 86400; - -/** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words. - * - * | Distance between dates | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance between dates | Result | - * |------------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWords( - * new Date(2014, 6, 2), - * new Date(2015, 0, 1) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00, including seconds? - * var result = distanceInWords( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWords( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> 'about 1 year ago' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWords( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ -function distanceInWords (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = Math.round(seconds / 60) - offset; - var months; - - // 0 up to 2 mins - if (minutes < 2) { - if (options.includeSeconds) { - if (seconds < 5) { - return localize('lessThanXSeconds', 5, localizeOptions) - } else if (seconds < 10) { - return localize('lessThanXSeconds', 10, localizeOptions) - } else if (seconds < 20) { - return localize('lessThanXSeconds', 20, localizeOptions) - } else if (seconds < 40) { - return localize('halfAMinute', null, localizeOptions) - } else if (seconds < 60) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', 1, localizeOptions) - } - } else { - if (minutes === 0) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', minutes, localizeOptions) - } - } - - // 2 mins up to 0.75 hrs - } else if (minutes < 45) { - return localize('xMinutes', minutes, localizeOptions) - - // 0.75 hrs up to 1.5 hrs - } else if (minutes < 90) { - return localize('aboutXHours', 1, localizeOptions) - - // 1.5 hrs up to 24 hrs - } else if (minutes < MINUTES_IN_DAY$1) { - var hours = Math.round(minutes / 60); - return localize('aboutXHours', hours, localizeOptions) - - // 1 day up to 1.75 days - } else if (minutes < MINUTES_IN_ALMOST_TWO_DAYS) { - return localize('xDays', 1, localizeOptions) - - // 1.75 days up to 30 days - } else if (minutes < MINUTES_IN_MONTH$1) { - var days = Math.round(minutes / MINUTES_IN_DAY$1); - return localize('xDays', days, localizeOptions) - - // 1 month up to 2 months - } else if (minutes < MINUTES_IN_TWO_MONTHS) { - months = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('aboutXMonths', months, localizeOptions) - } - - months = difference_in_months(dateRight, dateLeft); - - // 2 months up to 12 months - if (months < 12) { - var nearestMonth = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('xMonths', nearestMonth, localizeOptions) - - // 1 year up to max Date - } else { - var monthsSinceStartOfYear = months % 12; - var years = Math.floor(months / 12); - - // N years up to 1 years 3 months - if (monthsSinceStartOfYear < 3) { - return localize('aboutXYears', years, localizeOptions) - - // N years 3 months up to N years 9 months - } else if (monthsSinceStartOfYear < 9) { - return localize('overXYears', years, localizeOptions) - - // N years 9 months up to N year 12 months - } else { - return localize('almostXYears', years + 1, localizeOptions) - } - } -} - -var distance_in_words = distanceInWords; - -var MINUTES_IN_DAY = 1440; -var MINUTES_IN_MONTH = 43200; -var MINUTES_IN_YEAR = 525600; - -/** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words, using strict units. - * This is like `distanceInWords`, but does not use helpers like 'almost', 'over', - * 'less than' and the like. - * - * | Distance between dates | Result | - * |------------------------|---------------------| - * | 0 ... 59 secs | [0..59] seconds | - * | 1 ... 59 mins | [1..59] minutes | - * | 1 ... 23 hrs | [1..23] hours | - * | 1 ... 29 days | [1..29] days | - * | 1 ... 11 months | [1..11] months | - * | 1 ... N years | [1..N] years | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {'s'|'m'|'h'|'d'|'M'|'Y'} [options.unit] - if specified, will force a unit - * @param {'floor'|'ceil'|'round'} [options.partialMethod='floor'] - which way to round partial units - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWordsStrict( - * new Date(2014, 6, 2), - * new Date(2015, 0, 2) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * ) - * //=> '15 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> '1 year ago' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, in minutes? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {unit: 'm'} - * ) - * //=> '525600 minutes' - * - * @example - * // What is the distance from 1 January 2016 - * // to 28 January 2015, in months, rounded up? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 28), - * new Date(2015, 0, 1), - * {unit: 'M', partialMethod: 'ceil'} - * ) - * //=> '1 month' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsStrict( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> '1 jaro' - */ -function distanceInWordsStrict (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var unit; - var mathPartial = Math[options.partialMethod ? String(options.partialMethod) : 'floor']; - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = mathPartial(seconds / 60) - offset; - var hours, days, months, years; - - if (options.unit) { - unit = String(options.unit); - } else { - if (minutes < 1) { - unit = 's'; - } else if (minutes < 60) { - unit = 'm'; - } else if (minutes < MINUTES_IN_DAY) { - unit = 'h'; - } else if (minutes < MINUTES_IN_MONTH) { - unit = 'd'; - } else if (minutes < MINUTES_IN_YEAR) { - unit = 'M'; - } else { - unit = 'Y'; - } - } - - // 0 up to 60 seconds - if (unit === 's') { - return localize('xSeconds', seconds, localizeOptions) - - // 1 up to 60 mins - } else if (unit === 'm') { - return localize('xMinutes', minutes, localizeOptions) - - // 1 up to 24 hours - } else if (unit === 'h') { - hours = mathPartial(minutes / 60); - return localize('xHours', hours, localizeOptions) - - // 1 up to 30 days - } else if (unit === 'd') { - days = mathPartial(minutes / MINUTES_IN_DAY); - return localize('xDays', days, localizeOptions) - - // 1 up to 12 months - } else if (unit === 'M') { - months = mathPartial(minutes / MINUTES_IN_MONTH); - return localize('xMonths', months, localizeOptions) - - // 1 year up to max Date - } else if (unit === 'Y') { - years = mathPartial(minutes / MINUTES_IN_YEAR); - return localize('xYears', years, localizeOptions) - } - - throw new Error('Unknown unit: ' + unit) -} - -var distance_in_words_strict = distanceInWordsStrict; - -/** - * @category Common Helpers - * @summary Return the distance between the given date and now in words. - * - * @description - * Return the distance between the given date and now in words. - * - * | Distance to now | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance to now | Result | - * |---------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} date - the given date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result specifies if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // If today is 1 January 2015, what is the distance to 2 July 2014? - * var result = distanceInWordsToNow( - * new Date(2014, 6, 2) - * ) - * //=> '6 months' - * - * @example - * // If now is 1 January 2015 00:00:00, - * // what is the distance to 1 January 2015 00:00:15, including seconds? - * var result = distanceInWordsToNow( - * new Date(2015, 0, 1, 0, 0, 15), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 January 2016, with a suffix? - * var result = distanceInWordsToNow( - * new Date(2016, 0, 1), - * {addSuffix: true} - * ) - * //=> 'in about 1 year' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 August 2016 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsToNow( - * new Date(2016, 7, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ -function distanceInWordsToNow (dirtyDate, dirtyOptions) { - return distance_in_words(Date.now(), dirtyDate, dirtyOptions) -} - -var distance_in_words_to_now = distanceInWordsToNow; - -/** - * @category Day Helpers - * @summary Return the array of dates within the specified range. - * - * @description - * Return the array of dates within the specified range. - * - * @param {Date|String|Number} startDate - the first date - * @param {Date|String|Number} endDate - the last date - * @param {Number} [step=1] - the step between each day - * @returns {Date[]} the array with starts of days from the day of startDate to the day of endDate - * @throws {Error} startDate cannot be after endDate - * - * @example - * // Each day between 6 October 2014 and 10 October 2014: - * var result = eachDay( - * new Date(2014, 9, 6), - * new Date(2014, 9, 10) - * ) - * //=> [ - * // Mon Oct 06 2014 00:00:00, - * // Tue Oct 07 2014 00:00:00, - * // Wed Oct 08 2014 00:00:00, - * // Thu Oct 09 2014 00:00:00, - * // Fri Oct 10 2014 00:00:00 - * // ] - */ -function eachDay (dirtyStartDate, dirtyEndDate, dirtyStep) { - var startDate = parse_1(dirtyStartDate); - var endDate = parse_1(dirtyEndDate); - var step = dirtyStep !== undefined ? dirtyStep : 1; - - var endTime = endDate.getTime(); - - if (startDate.getTime() > endTime) { - throw new Error('The first date cannot be after the second date') - } - - var dates = []; - - var currentDate = startDate; - currentDate.setHours(0, 0, 0, 0); - - while (currentDate.getTime() <= endTime) { - dates.push(parse_1(currentDate)); - currentDate.setDate(currentDate.getDate() + step); - } - - return dates -} - -var each_day = eachDay; - -/** - * @category Day Helpers - * @summary Return the end of a day for the given date. - * - * @description - * Return the end of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a day - * - * @example - * // The end of a day for 2 September 2014 11:55:00: - * var result = endOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 23:59:59.999 - */ -function endOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_day = endOfDay; - -/** - * @category Hour Helpers - * @summary Return the end of an hour for the given date. - * - * @description - * Return the end of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an hour - * - * @example - * // The end of an hour for 2 September 2014 11:55:00: - * var result = endOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:59:59.999 - */ -function endOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(59, 59, 999); - return date -} - -var end_of_hour = endOfHour; - -/** - * @category Week Helpers - * @summary Return the end of a week for the given date. - * - * @description - * Return the end of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the end of a week - * - * @example - * // The end of a week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 23:59:59.999 - * - * @example - * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 23:59:59.999 - */ -function endOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setDate(date.getDate() + diff); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_week = endOfWeek; - -/** - * @category ISO Week Helpers - * @summary Return the end of an ISO week for the given date. - * - * @description - * Return the end of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week - * - * @example - * // The end of an ISO week for 2 September 2014 11:55:00: - * var result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 23:59:59.999 - */ -function endOfISOWeek (dirtyDate) { - return end_of_week(dirtyDate, {weekStartsOn: 1}) -} - -var end_of_iso_week = endOfISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Return the end of an ISO week-numbering year for the given date. - * - * @description - * Return the end of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The end of an ISO week-numbering year for 2 July 2005: - * var result = endOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 23:59:59.999 - */ -function endOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuaryOfNextYear); - date.setMilliseconds(date.getMilliseconds() - 1); - return date -} - -var end_of_iso_year = endOfISOYear; - -/** - * @category Minute Helpers - * @summary Return the end of a minute for the given date. - * - * @description - * Return the end of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a minute - * - * @example - * // The end of a minute for 1 December 2014 22:15:45.400: - * var result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:59.999 - */ -function endOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(59, 999); - return date -} - -var end_of_minute = endOfMinute; - -/** - * @category Month Helpers - * @summary Return the end of a month for the given date. - * - * @description - * Return the end of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a month - * - * @example - * // The end of a month for 2 September 2014 11:55:00: - * var result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ -function endOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_month = endOfMonth; - -/** - * @category Quarter Helpers - * @summary Return the end of a year quarter for the given date. - * - * @description - * Return the end of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a quarter - * - * @example - * // The end of a quarter for 2 September 2014 11:55:00: - * var result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ -function endOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_quarter = endOfQuarter; - -/** - * @category Second Helpers - * @summary Return the end of a second for the given date. - * - * @description - * Return the end of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a second - * - * @example - * // The end of a second for 1 December 2014 22:15:45.400: - * var result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.999 - */ -function endOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(999); - return date -} - -var end_of_second = endOfSecond; - -/** - * @category Day Helpers - * @summary Return the end of today. - * - * @description - * Return the end of today. - * - * @returns {Date} the end of today - * - * @example - * // If today is 6 October 2014: - * var result = endOfToday() - * //=> Mon Oct 6 2014 23:59:59.999 - */ -function endOfToday () { - return end_of_day(new Date()) -} - -var end_of_today = endOfToday; - -/** - * @category Day Helpers - * @summary Return the end of tomorrow. - * - * @description - * Return the end of tomorrow. - * - * @returns {Date} the end of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = endOfTomorrow() - * //=> Tue Oct 7 2014 23:59:59.999 - */ -function endOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_tomorrow = endOfTomorrow; - -/** - * @category Year Helpers - * @summary Return the end of a year for the given date. - * - * @description - * Return the end of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a year - * - * @example - * // The end of a year for 2 September 2014 11:55:00: - * var result = endOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 23:59:59.999 - */ -function endOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_year = endOfYear; - -/** - * @category Day Helpers - * @summary Return the end of yesterday. - * - * @description - * Return the end of yesterday. - * - * @returns {Date} the end of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = endOfYesterday() - * //=> Sun Oct 5 2014 23:59:59.999 - */ -function endOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_yesterday = endOfYesterday; - -/** - * @category Year Helpers - * @summary Return the start of a year for the given date. - * - * @description - * Return the start of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a year - * - * @example - * // The start of a year for 2 September 2014 11:55:00: - * var result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Jan 01 2014 00:00:00 - */ -function startOfYear (dirtyDate) { - var cleanDate = parse_1(dirtyDate); - var date = new Date(0); - date.setFullYear(cleanDate.getFullYear(), 0, 1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_year = startOfYear; - -/** - * @category Day Helpers - * @summary Get the day of the year of the given date. - * - * @description - * Get the day of the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of year - * - * @example - * // Which day of the year is 2 July 2014? - * var result = getDayOfYear(new Date(2014, 6, 2)) - * //=> 183 - */ -function getDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = difference_in_calendar_days(date, start_of_year(date)); - var dayOfYear = diff + 1; - return dayOfYear -} - -var get_day_of_year = getDayOfYear; - -var MILLISECONDS_IN_WEEK$1 = 604800000; - -/** - * @category ISO Week Helpers - * @summary Get the ISO week of the given date. - * - * @description - * Get the ISO week of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week - * - * @example - * // Which week of the ISO-week numbering year is 2 January 2005? - * var result = getISOWeek(new Date(2005, 0, 2)) - * //=> 53 - */ -function getISOWeek (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = start_of_iso_week(date).getTime() - start_of_iso_year(date).getTime(); - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1 -} - -var get_iso_week = getISOWeek; - -/** - * @category Common Helpers - * @summary Is the given date valid? - * - * @description - * Returns false if argument is Invalid Date and true otherwise. - * Invalid Date is a Date, whose time value is NaN. - * - * Time value of Date: http://es5.github.io/#x15.9.1.1 - * - * @param {Date} date - the date to check - * @returns {Boolean} the date is valid - * @throws {TypeError} argument must be an instance of Date - * - * @example - * // For the valid date: - * var result = isValid(new Date(2014, 1, 31)) - * //=> true - * - * @example - * // For the invalid date: - * var result = isValid(new Date('')) - * //=> false - */ -function isValid (dirtyDate) { - if (is_date(dirtyDate)) { - return !isNaN(dirtyDate) - } else { - throw new TypeError(toString.call(dirtyDate) + ' is not an instance of Date') - } -} - -var is_valid = isValid; - -/** - * @category Common Helpers - * @summary Format the date. - * - * @description - * Return the formatted date string in the given format. - * - * Accepted tokens: - * | Unit | Token | Result examples | - * |-------------------------|-------|----------------------------------| - * | Month | M | 1, 2, ..., 12 | - * | | Mo | 1st, 2nd, ..., 12th | - * | | MM | 01, 02, ..., 12 | - * | | MMM | Jan, Feb, ..., Dec | - * | | MMMM | January, February, ..., December | - * | Quarter | Q | 1, 2, 3, 4 | - * | | Qo | 1st, 2nd, 3rd, 4th | - * | Day of month | D | 1, 2, ..., 31 | - * | | Do | 1st, 2nd, ..., 31st | - * | | DD | 01, 02, ..., 31 | - * | Day of year | DDD | 1, 2, ..., 366 | - * | | DDDo | 1st, 2nd, ..., 366th | - * | | DDDD | 001, 002, ..., 366 | - * | Day of week | d | 0, 1, ..., 6 | - * | | do | 0th, 1st, ..., 6th | - * | | dd | Su, Mo, ..., Sa | - * | | ddd | Sun, Mon, ..., Sat | - * | | dddd | Sunday, Monday, ..., Saturday | - * | Day of ISO week | E | 1, 2, ..., 7 | - * | ISO week | W | 1, 2, ..., 53 | - * | | Wo | 1st, 2nd, ..., 53rd | - * | | WW | 01, 02, ..., 53 | - * | Year | YY | 00, 01, ..., 99 | - * | | YYYY | 1900, 1901, ..., 2099 | - * | ISO week-numbering year | GG | 00, 01, ..., 99 | - * | | GGGG | 1900, 1901, ..., 2099 | - * | AM/PM | A | AM, PM | - * | | a | am, pm | - * | | aa | a.m., p.m. | - * | Hour | H | 0, 1, ... 23 | - * | | HH | 00, 01, ... 23 | - * | | h | 1, 2, ..., 12 | - * | | hh | 01, 02, ..., 12 | - * | Minute | m | 0, 1, ..., 59 | - * | | mm | 00, 01, ..., 59 | - * | Second | s | 0, 1, ..., 59 | - * | | ss | 00, 01, ..., 59 | - * | 1/10 of second | S | 0, 1, ..., 9 | - * | 1/100 of second | SS | 00, 01, ..., 99 | - * | Millisecond | SSS | 000, 001, ..., 999 | - * | Timezone | Z | -01:00, +00:00, ... +12:00 | - * | | ZZ | -0100, +0000, ..., +1200 | - * | Seconds timestamp | X | 512969520 | - * | Milliseconds timestamp | x | 512969520900 | - * - * The characters wrapped in square brackets are escaped. - * - * The result may vary by locale. - * - * @param {Date|String|Number} date - the original date - * @param {String} [format='YYYY-MM-DDTHH:mm:ss.SSSZ'] - the string of tokens - * @param {Object} [options] - the object with options - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the formatted date string - * - * @example - * // Represent 11 February 2014 in middle-endian format: - * var result = format( - * new Date(2014, 1, 11), - * 'MM/DD/YYYY' - * ) - * //=> '02/11/2014' - * - * @example - * // Represent 2 July 2014 in Esperanto: - * var eoLocale = require('date-fns/locale/eo') - * var result = format( - * new Date(2014, 6, 2), - * 'Do [de] MMMM YYYY', - * {locale: eoLocale} - * ) - * //=> '2-a de julio 2014' - */ -function format (dirtyDate, dirtyFormatStr, dirtyOptions) { - var formatStr = dirtyFormatStr ? String(dirtyFormatStr) : 'YYYY-MM-DDTHH:mm:ss.SSSZ'; - var options = dirtyOptions || {}; - - var locale = options.locale; - var localeFormatters = en.format.formatters; - var formattingTokensRegExp = en.format.formattingTokensRegExp; - if (locale && locale.format && locale.format.formatters) { - localeFormatters = locale.format.formatters; - - if (locale.format.formattingTokensRegExp) { - formattingTokensRegExp = locale.format.formattingTokensRegExp; - } - } - - var date = parse_1(dirtyDate); - - if (!is_valid(date)) { - return 'Invalid Date' - } - - var formatFn = buildFormatFn(formatStr, localeFormatters, formattingTokensRegExp); - - return formatFn(date) -} - -var formatters = { - // Month: 1, 2, ..., 12 - 'M': function (date) { - return date.getMonth() + 1 - }, - - // Month: 01, 02, ..., 12 - 'MM': function (date) { - return addLeadingZeros(date.getMonth() + 1, 2) - }, - - // Quarter: 1, 2, 3, 4 - 'Q': function (date) { - return Math.ceil((date.getMonth() + 1) / 3) - }, - - // Day of month: 1, 2, ..., 31 - 'D': function (date) { - return date.getDate() - }, - - // Day of month: 01, 02, ..., 31 - 'DD': function (date) { - return addLeadingZeros(date.getDate(), 2) - }, - - // Day of year: 1, 2, ..., 366 - 'DDD': function (date) { - return get_day_of_year(date) - }, - - // Day of year: 001, 002, ..., 366 - 'DDDD': function (date) { - return addLeadingZeros(get_day_of_year(date), 3) - }, - - // Day of week: 0, 1, ..., 6 - 'd': function (date) { - return date.getDay() - }, - - // Day of ISO week: 1, 2, ..., 7 - 'E': function (date) { - return date.getDay() || 7 - }, - - // ISO week: 1, 2, ..., 53 - 'W': function (date) { - return get_iso_week(date) - }, - - // ISO week: 01, 02, ..., 53 - 'WW': function (date) { - return addLeadingZeros(get_iso_week(date), 2) - }, - - // Year: 00, 01, ..., 99 - 'YY': function (date) { - return addLeadingZeros(date.getFullYear(), 4).substr(2) - }, - - // Year: 1900, 1901, ..., 2099 - 'YYYY': function (date) { - return addLeadingZeros(date.getFullYear(), 4) - }, - - // ISO week-numbering year: 00, 01, ..., 99 - 'GG': function (date) { - return String(get_iso_year(date)).substr(2) - }, - - // ISO week-numbering year: 1900, 1901, ..., 2099 - 'GGGG': function (date) { - return get_iso_year(date) - }, - - // Hour: 0, 1, ... 23 - 'H': function (date) { - return date.getHours() - }, - - // Hour: 00, 01, ..., 23 - 'HH': function (date) { - return addLeadingZeros(date.getHours(), 2) - }, - - // Hour: 1, 2, ..., 12 - 'h': function (date) { - var hours = date.getHours(); - if (hours === 0) { - return 12 - } else if (hours > 12) { - return hours % 12 - } else { - return hours - } - }, - - // Hour: 01, 02, ..., 12 - 'hh': function (date) { - return addLeadingZeros(formatters['h'](date), 2) - }, - - // Minute: 0, 1, ..., 59 - 'm': function (date) { - return date.getMinutes() - }, - - // Minute: 00, 01, ..., 59 - 'mm': function (date) { - return addLeadingZeros(date.getMinutes(), 2) - }, - - // Second: 0, 1, ..., 59 - 's': function (date) { - return date.getSeconds() - }, - - // Second: 00, 01, ..., 59 - 'ss': function (date) { - return addLeadingZeros(date.getSeconds(), 2) - }, - - // 1/10 of second: 0, 1, ..., 9 - 'S': function (date) { - return Math.floor(date.getMilliseconds() / 100) - }, - - // 1/100 of second: 00, 01, ..., 99 - 'SS': function (date) { - return addLeadingZeros(Math.floor(date.getMilliseconds() / 10), 2) - }, - - // Millisecond: 000, 001, ..., 999 - 'SSS': function (date) { - return addLeadingZeros(date.getMilliseconds(), 3) - }, - - // Timezone: -01:00, +00:00, ... +12:00 - 'Z': function (date) { - return formatTimezone(date.getTimezoneOffset(), ':') - }, - - // Timezone: -0100, +0000, ... +1200 - 'ZZ': function (date) { - return formatTimezone(date.getTimezoneOffset()) - }, - - // Seconds timestamp: 512969520 - 'X': function (date) { - return Math.floor(date.getTime() / 1000) - }, - - // Milliseconds timestamp: 512969520900 - 'x': function (date) { - return date.getTime() - } -}; - -function buildFormatFn (formatStr, localeFormatters, formattingTokensRegExp) { - var array = formatStr.match(formattingTokensRegExp); - var length = array.length; - - var i; - var formatter; - for (i = 0; i < length; i++) { - formatter = localeFormatters[array[i]] || formatters[array[i]]; - if (formatter) { - array[i] = formatter; - } else { - array[i] = removeFormattingTokens(array[i]); - } - } - - return function (date) { - var output = ''; - for (var i = 0; i < length; i++) { - if (array[i] instanceof Function) { - output += array[i](date, formatters); - } else { - output += array[i]; - } - } - return output - } -} - -function removeFormattingTokens (input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|]$/g, '') - } - return input.replace(/\\/g, '') -} - -function formatTimezone (offset, delimeter) { - delimeter = delimeter || ''; - var sign = offset > 0 ? '-' : '+'; - var absOffset = Math.abs(offset); - var hours = Math.floor(absOffset / 60); - var minutes = absOffset % 60; - return sign + addLeadingZeros(hours, 2) + delimeter + addLeadingZeros(minutes, 2) -} - -function addLeadingZeros (number, targetLength) { - var output = Math.abs(number).toString(); - while (output.length < targetLength) { - output = '0' + output; - } - return output -} - -var format_1 = format; - -/** - * @category Day Helpers - * @summary Get the day of the month of the given date. - * - * @description - * Get the day of the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of month - * - * @example - * // Which day of the month is 29 February 2012? - * var result = getDate(new Date(2012, 1, 29)) - * //=> 29 - */ -function getDate (dirtyDate) { - var date = parse_1(dirtyDate); - var dayOfMonth = date.getDate(); - return dayOfMonth -} - -var get_date = getDate; - -/** - * @category Weekday Helpers - * @summary Get the day of the week of the given date. - * - * @description - * Get the day of the week of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of week - * - * @example - * // Which day of the week is 29 February 2012? - * var result = getDay(new Date(2012, 1, 29)) - * //=> 3 - */ -function getDay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day -} - -var get_day = getDay; - -/** - * @category Year Helpers - * @summary Is the given date in the leap year? - * - * @description - * Is the given date in the leap year? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the leap year - * - * @example - * // Is 1 September 2012 in the leap year? - * var result = isLeapYear(new Date(2012, 8, 1)) - * //=> true - */ -function isLeapYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0 -} - -var is_leap_year = isLeapYear; - -/** - * @category Year Helpers - * @summary Get the number of days in a year of the given date. - * - * @description - * Get the number of days in a year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a year - * - * @example - * // How many days are in 2012? - * var result = getDaysInYear(new Date(2012, 0, 1)) - * //=> 366 - */ -function getDaysInYear (dirtyDate) { - return is_leap_year(dirtyDate) ? 366 : 365 -} - -var get_days_in_year = getDaysInYear; - -/** - * @category Hour Helpers - * @summary Get the hours of the given date. - * - * @description - * Get the hours of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the hours - * - * @example - * // Get the hours of 29 February 2012 11:45:00: - * var result = getHours(new Date(2012, 1, 29, 11, 45)) - * //=> 11 - */ -function getHours (dirtyDate) { - var date = parse_1(dirtyDate); - var hours = date.getHours(); - return hours -} - -var get_hours = getHours; - -/** - * @category Weekday Helpers - * @summary Get the day of the ISO week of the given date. - * - * @description - * Get the day of the ISO week of the given date, - * which is 7 for Sunday, 1 for Monday etc. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of ISO week - * - * @example - * // Which day of the ISO week is 26 February 2012? - * var result = getISODay(new Date(2012, 1, 26)) - * //=> 7 - */ -function getISODay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - - if (day === 0) { - day = 7; - } - - return day -} - -var get_iso_day = getISODay; - -var MILLISECONDS_IN_WEEK = 604800000; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of weeks in an ISO week-numbering year of the given date. - * - * @description - * Get the number of weeks in an ISO week-numbering year of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of ISO weeks in a year - * - * @example - * // How many weeks are in ISO week-numbering year 2015? - * var result = getISOWeeksInYear(new Date(2015, 1, 11)) - * //=> 53 - */ -function getISOWeeksInYear (dirtyDate) { - var thisYear = start_of_iso_year(dirtyDate); - var nextYear = start_of_iso_year(add_weeks(thisYear, 60)); - var diff = nextYear.valueOf() - thisYear.valueOf(); - // Round the number of weeks to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK) -} - -var get_iso_weeks_in_year = getISOWeeksInYear; - -/** - * @category Millisecond Helpers - * @summary Get the milliseconds of the given date. - * - * @description - * Get the milliseconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the milliseconds - * - * @example - * // Get the milliseconds of 29 February 2012 11:45:05.123: - * var result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 123 - */ -function getMilliseconds (dirtyDate) { - var date = parse_1(dirtyDate); - var milliseconds = date.getMilliseconds(); - return milliseconds -} - -var get_milliseconds = getMilliseconds; - -/** - * @category Minute Helpers - * @summary Get the minutes of the given date. - * - * @description - * Get the minutes of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the minutes - * - * @example - * // Get the minutes of 29 February 2012 11:45:05: - * var result = getMinutes(new Date(2012, 1, 29, 11, 45, 5)) - * //=> 45 - */ -function getMinutes (dirtyDate) { - var date = parse_1(dirtyDate); - var minutes = date.getMinutes(); - return minutes -} - -var get_minutes = getMinutes; - -/** - * @category Month Helpers - * @summary Get the month of the given date. - * - * @description - * Get the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the month - * - * @example - * // Which month is 29 February 2012? - * var result = getMonth(new Date(2012, 1, 29)) - * //=> 1 - */ -function getMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - return month -} - -var get_month = getMonth; - -var MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000; - -/** - * @category Range Helpers - * @summary Get the number of days that overlap in two date ranges - * - * @description - * Get the number of days that overlap in two date ranges - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Number} the number of days that overlap in two date ranges - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges adds 1 for each started overlapping day: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> 3 - * - * @example - * // For non-overlapping date ranges returns 0: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> 0 - */ -function getOverlappingDaysInRanges (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - var isOverlapping = initialStartTime < comparedEndTime && comparedStartTime < initialEndTime; - - if (!isOverlapping) { - return 0 - } - - var overlapStartDate = comparedStartTime < initialStartTime - ? initialStartTime - : comparedStartTime; - - var overlapEndDate = comparedEndTime > initialEndTime - ? initialEndTime - : comparedEndTime; - - var differenceInMs = overlapEndDate - overlapStartDate; - - return Math.ceil(differenceInMs / MILLISECONDS_IN_DAY) -} - -var get_overlapping_days_in_ranges = getOverlappingDaysInRanges; - -/** - * @category Second Helpers - * @summary Get the seconds of the given date. - * - * @description - * Get the seconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the seconds - * - * @example - * // Get the seconds of 29 February 2012 11:45:05.123: - * var result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 5 - */ -function getSeconds (dirtyDate) { - var date = parse_1(dirtyDate); - var seconds = date.getSeconds(); - return seconds -} - -var get_seconds = getSeconds; - -/** - * @category Timestamp Helpers - * @summary Get the milliseconds timestamp of the given date. - * - * @description - * Get the milliseconds timestamp of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the timestamp - * - * @example - * // Get the timestamp of 29 February 2012 11:45:05.123: - * var result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 1330515905123 - */ -function getTime (dirtyDate) { - var date = parse_1(dirtyDate); - var timestamp = date.getTime(); - return timestamp -} - -var get_time = getTime; - -/** - * @category Year Helpers - * @summary Get the year of the given date. - * - * @description - * Get the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the year - * - * @example - * // Which year is 2 July 2014? - * var result = getYear(new Date(2014, 6, 2)) - * //=> 2014 - */ -function getYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year -} - -var get_year = getYear; - -/** - * @category Common Helpers - * @summary Is the first date after the second one? - * - * @description - * Is the first date after the second one? - * - * @param {Date|String|Number} date - the date that should be after the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is after the second date - * - * @example - * // Is 10 July 1989 after 11 February 1987? - * var result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> true - */ -function isAfter (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() > dateToCompare.getTime() -} - -var is_after = isAfter; - -/** - * @category Common Helpers - * @summary Is the first date before the second one? - * - * @description - * Is the first date before the second one? - * - * @param {Date|String|Number} date - the date that should be before the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is before the second date - * - * @example - * // Is 10 July 1989 before 11 February 1987? - * var result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> false - */ -function isBefore (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() < dateToCompare.getTime() -} - -var is_before = isBefore; - -/** - * @category Common Helpers - * @summary Are the given dates equal? - * - * @description - * Are the given dates equal? - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Boolean} the dates are equal - * - * @example - * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal? - * var result = isEqual( - * new Date(2014, 6, 2, 6, 30, 45, 0) - * new Date(2014, 6, 2, 6, 30, 45, 500) - * ) - * //=> false - */ -function isEqual (dirtyLeftDate, dirtyRightDate) { - var dateLeft = parse_1(dirtyLeftDate); - var dateRight = parse_1(dirtyRightDate); - return dateLeft.getTime() === dateRight.getTime() -} - -var is_equal = isEqual; - -/** - * @category Month Helpers - * @summary Is the given date the first day of a month? - * - * @description - * Is the given date the first day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the first day of a month - * - * @example - * // Is 1 September 2014 the first day of a month? - * var result = isFirstDayOfMonth(new Date(2014, 8, 1)) - * //=> true - */ -function isFirstDayOfMonth (dirtyDate) { - return parse_1(dirtyDate).getDate() === 1 -} - -var is_first_day_of_month = isFirstDayOfMonth; - -/** - * @category Weekday Helpers - * @summary Is the given date Friday? - * - * @description - * Is the given date Friday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Friday - * - * @example - * // Is 26 September 2014 Friday? - * var result = isFriday(new Date(2014, 8, 26)) - * //=> true - */ -function isFriday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 5 -} - -var is_friday = isFriday; - -/** - * @category Common Helpers - * @summary Is the given date in the future? - * - * @description - * Is the given date in the future? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the future - * - * @example - * // If today is 6 October 2014, is 31 December 2014 in the future? - * var result = isFuture(new Date(2014, 11, 31)) - * //=> true - */ -function isFuture (dirtyDate) { - return parse_1(dirtyDate).getTime() > new Date().getTime() -} - -var is_future = isFuture; - -/** - * @category Month Helpers - * @summary Is the given date the last day of a month? - * - * @description - * Is the given date the last day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the last day of a month - * - * @example - * // Is 28 February 2014 the last day of a month? - * var result = isLastDayOfMonth(new Date(2014, 1, 28)) - * //=> true - */ -function isLastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - return end_of_day(date).getTime() === end_of_month(date).getTime() -} - -var is_last_day_of_month = isLastDayOfMonth; - -/** - * @category Weekday Helpers - * @summary Is the given date Monday? - * - * @description - * Is the given date Monday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Monday - * - * @example - * // Is 22 September 2014 Monday? - * var result = isMonday(new Date(2014, 8, 22)) - * //=> true - */ -function isMonday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 1 -} - -var is_monday = isMonday; - -/** - * @category Common Helpers - * @summary Is the given date in the past? - * - * @description - * Is the given date in the past? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the past - * - * @example - * // If today is 6 October 2014, is 2 July 2014 in the past? - * var result = isPast(new Date(2014, 6, 2)) - * //=> true - */ -function isPast (dirtyDate) { - return parse_1(dirtyDate).getTime() < new Date().getTime() -} - -var is_past = isPast; - -/** - * @category Day Helpers - * @summary Are the given dates in the same day? - * - * @description - * Are the given dates in the same day? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same day - * - * @example - * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? - * var result = isSameDay( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 18, 0) - * ) - * //=> true - */ -function isSameDay (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfDay = start_of_day(dirtyDateLeft); - var dateRightStartOfDay = start_of_day(dirtyDateRight); - - return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime() -} - -var is_same_day = isSameDay; - -/** - * @category Hour Helpers - * @summary Return the start of an hour for the given date. - * - * @description - * Return the start of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an hour - * - * @example - * // The start of an hour for 2 September 2014 11:55:00: - * var result = startOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:00:00 - */ -function startOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(0, 0, 0); - return date -} - -var start_of_hour = startOfHour; - -/** - * @category Hour Helpers - * @summary Are the given dates in the same hour? - * - * @description - * Are the given dates in the same hour? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same hour - * - * @example - * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour? - * var result = isSameHour( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 6, 30) - * ) - * //=> true - */ -function isSameHour (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfHour = start_of_hour(dirtyDateLeft); - var dateRightStartOfHour = start_of_hour(dirtyDateRight); - - return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime() -} - -var is_same_hour = isSameHour; - -/** - * @category Week Helpers - * @summary Are the given dates in the same week? - * - * @description - * Are the given dates in the same week? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the dates are in the same week - * - * @example - * // Are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4) - * ) - * //=> true - * - * @example - * // If week starts with Monday, - * // are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4), - * {weekStartsOn: 1} - * ) - * //=> false - */ -function isSameWeek (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var dateLeftStartOfWeek = start_of_week(dirtyDateLeft, dirtyOptions); - var dateRightStartOfWeek = start_of_week(dirtyDateRight, dirtyOptions); - - return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime() -} - -var is_same_week = isSameWeek; - -/** - * @category ISO Week Helpers - * @summary Are the given dates in the same ISO week? - * - * @description - * Are the given dates in the same ISO week? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week - * - * @example - * // Are 1 September 2014 and 7 September 2014 in the same ISO week? - * var result = isSameISOWeek( - * new Date(2014, 8, 1), - * new Date(2014, 8, 7) - * ) - * //=> true - */ -function isSameISOWeek (dirtyDateLeft, dirtyDateRight) { - return is_same_week(dirtyDateLeft, dirtyDateRight, {weekStartsOn: 1}) -} - -var is_same_iso_week = isSameISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Are the given dates in the same ISO week-numbering year? - * - * @description - * Are the given dates in the same ISO week-numbering year? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week-numbering year - * - * @example - * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? - * var result = isSameISOYear( - * new Date(2003, 11, 29), - * new Date(2005, 0, 2) - * ) - * //=> true - */ -function isSameISOYear (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfYear = start_of_iso_year(dirtyDateLeft); - var dateRightStartOfYear = start_of_iso_year(dirtyDateRight); - - return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime() -} - -var is_same_iso_year = isSameISOYear; - -/** - * @category Minute Helpers - * @summary Return the start of a minute for the given date. - * - * @description - * Return the start of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a minute - * - * @example - * // The start of a minute for 1 December 2014 22:15:45.400: - * var result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:00 - */ -function startOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(0, 0); - return date -} - -var start_of_minute = startOfMinute; - -/** - * @category Minute Helpers - * @summary Are the given dates in the same minute? - * - * @description - * Are the given dates in the same minute? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same minute - * - * @example - * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 - * // in the same minute? - * var result = isSameMinute( - * new Date(2014, 8, 4, 6, 30), - * new Date(2014, 8, 4, 6, 30, 15) - * ) - * //=> true - */ -function isSameMinute (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfMinute = start_of_minute(dirtyDateLeft); - var dateRightStartOfMinute = start_of_minute(dirtyDateRight); - - return dateLeftStartOfMinute.getTime() === dateRightStartOfMinute.getTime() -} - -var is_same_minute = isSameMinute; - -/** - * @category Month Helpers - * @summary Are the given dates in the same month? - * - * @description - * Are the given dates in the same month? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same month - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same month? - * var result = isSameMonth( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ -function isSameMonth (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() && - dateLeft.getMonth() === dateRight.getMonth() -} - -var is_same_month = isSameMonth; - -/** - * @category Quarter Helpers - * @summary Return the start of a year quarter for the given date. - * - * @description - * Return the start of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a quarter - * - * @example - * // The start of a quarter for 2 September 2014 11:55:00: - * var result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Jul 01 2014 00:00:00 - */ -function startOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3; - date.setMonth(month, 1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_quarter = startOfQuarter; - -/** - * @category Quarter Helpers - * @summary Are the given dates in the same year quarter? - * - * @description - * Are the given dates in the same year quarter? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same quarter - * - * @example - * // Are 1 January 2014 and 8 March 2014 in the same quarter? - * var result = isSameQuarter( - * new Date(2014, 0, 1), - * new Date(2014, 2, 8) - * ) - * //=> true - */ -function isSameQuarter (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfQuarter = start_of_quarter(dirtyDateLeft); - var dateRightStartOfQuarter = start_of_quarter(dirtyDateRight); - - return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime() -} - -var is_same_quarter = isSameQuarter; - -/** - * @category Second Helpers - * @summary Return the start of a second for the given date. - * - * @description - * Return the start of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a second - * - * @example - * // The start of a second for 1 December 2014 22:15:45.400: - * var result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.000 - */ -function startOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(0); - return date -} - -var start_of_second = startOfSecond; - -/** - * @category Second Helpers - * @summary Are the given dates in the same second? - * - * @description - * Are the given dates in the same second? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same second - * - * @example - * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 - * // in the same second? - * var result = isSameSecond( - * new Date(2014, 8, 4, 6, 30, 15), - * new Date(2014, 8, 4, 6, 30, 15, 500) - * ) - * //=> true - */ -function isSameSecond (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfSecond = start_of_second(dirtyDateLeft); - var dateRightStartOfSecond = start_of_second(dirtyDateRight); - - return dateLeftStartOfSecond.getTime() === dateRightStartOfSecond.getTime() -} - -var is_same_second = isSameSecond; - -/** - * @category Year Helpers - * @summary Are the given dates in the same year? - * - * @description - * Are the given dates in the same year? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same year - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same year? - * var result = isSameYear( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ -function isSameYear (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() -} - -var is_same_year = isSameYear; - -/** - * @category Weekday Helpers - * @summary Is the given date Saturday? - * - * @description - * Is the given date Saturday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Saturday - * - * @example - * // Is 27 September 2014 Saturday? - * var result = isSaturday(new Date(2014, 8, 27)) - * //=> true - */ -function isSaturday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 6 -} - -var is_saturday = isSaturday; - -/** - * @category Weekday Helpers - * @summary Is the given date Sunday? - * - * @description - * Is the given date Sunday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Sunday - * - * @example - * // Is 21 September 2014 Sunday? - * var result = isSunday(new Date(2014, 8, 21)) - * //=> true - */ -function isSunday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 0 -} - -var is_sunday = isSunday; - -/** - * @category Hour Helpers - * @summary Is the given date in the same hour as the current date? - * - * @description - * Is the given date in the same hour as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this hour - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:00:00 in this hour? - * var result = isThisHour(new Date(2014, 8, 25, 18)) - * //=> true - */ -function isThisHour (dirtyDate) { - return is_same_hour(new Date(), dirtyDate) -} - -var is_this_hour = isThisHour; - -/** - * @category ISO Week Helpers - * @summary Is the given date in the same ISO week as the current date? - * - * @description - * Is the given date in the same ISO week as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week - * - * @example - * // If today is 25 September 2014, is 22 September 2014 in this ISO week? - * var result = isThisISOWeek(new Date(2014, 8, 22)) - * //=> true - */ -function isThisISOWeek (dirtyDate) { - return is_same_iso_week(new Date(), dirtyDate) -} - -var is_this_iso_week = isThisISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Is the given date in the same ISO week-numbering year as the current date? - * - * @description - * Is the given date in the same ISO week-numbering year as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week-numbering year - * - * @example - * // If today is 25 September 2014, - * // is 30 December 2013 in this ISO week-numbering year? - * var result = isThisISOYear(new Date(2013, 11, 30)) - * //=> true - */ -function isThisISOYear (dirtyDate) { - return is_same_iso_year(new Date(), dirtyDate) -} - -var is_this_iso_year = isThisISOYear; - -/** - * @category Minute Helpers - * @summary Is the given date in the same minute as the current date? - * - * @description - * Is the given date in the same minute as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this minute - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:00 in this minute? - * var result = isThisMinute(new Date(2014, 8, 25, 18, 30)) - * //=> true - */ -function isThisMinute (dirtyDate) { - return is_same_minute(new Date(), dirtyDate) -} - -var is_this_minute = isThisMinute; - -/** - * @category Month Helpers - * @summary Is the given date in the same month as the current date? - * - * @description - * Is the given date in the same month as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this month - * - * @example - * // If today is 25 September 2014, is 15 September 2014 in this month? - * var result = isThisMonth(new Date(2014, 8, 15)) - * //=> true - */ -function isThisMonth (dirtyDate) { - return is_same_month(new Date(), dirtyDate) -} - -var is_this_month = isThisMonth; - -/** - * @category Quarter Helpers - * @summary Is the given date in the same quarter as the current date? - * - * @description - * Is the given date in the same quarter as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this quarter - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this quarter? - * var result = isThisQuarter(new Date(2014, 6, 2)) - * //=> true - */ -function isThisQuarter (dirtyDate) { - return is_same_quarter(new Date(), dirtyDate) -} - -var is_this_quarter = isThisQuarter; - -/** - * @category Second Helpers - * @summary Is the given date in the same second as the current date? - * - * @description - * Is the given date in the same second as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this second - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:15.000 in this second? - * var result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15)) - * //=> true - */ -function isThisSecond (dirtyDate) { - return is_same_second(new Date(), dirtyDate) -} - -var is_this_second = isThisSecond; - -/** - * @category Week Helpers - * @summary Is the given date in the same week as the current date? - * - * @description - * Is the given date in the same week as the current date? - * - * @param {Date|String|Number} date - the date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the date is in this week - * - * @example - * // If today is 25 September 2014, is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21)) - * //=> true - * - * @example - * // If today is 25 September 2014 and week starts with Monday - * // is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21), {weekStartsOn: 1}) - * //=> false - */ -function isThisWeek (dirtyDate, dirtyOptions) { - return is_same_week(new Date(), dirtyDate, dirtyOptions) -} - -var is_this_week = isThisWeek; - -/** - * @category Year Helpers - * @summary Is the given date in the same year as the current date? - * - * @description - * Is the given date in the same year as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this year - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this year? - * var result = isThisYear(new Date(2014, 6, 2)) - * //=> true - */ -function isThisYear (dirtyDate) { - return is_same_year(new Date(), dirtyDate) -} - -var is_this_year = isThisYear; - -/** - * @category Weekday Helpers - * @summary Is the given date Thursday? - * - * @description - * Is the given date Thursday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Thursday - * - * @example - * // Is 25 September 2014 Thursday? - * var result = isThursday(new Date(2014, 8, 25)) - * //=> true - */ -function isThursday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 4 -} - -var is_thursday = isThursday; - -/** - * @category Day Helpers - * @summary Is the given date today? - * - * @description - * Is the given date today? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is today - * - * @example - * // If today is 6 October 2014, is 6 October 14:00:00 today? - * var result = isToday(new Date(2014, 9, 6, 14, 0)) - * //=> true - */ -function isToday (dirtyDate) { - return start_of_day(dirtyDate).getTime() === start_of_day(new Date()).getTime() -} - -var is_today = isToday; - -/** - * @category Day Helpers - * @summary Is the given date tomorrow? - * - * @description - * Is the given date tomorrow? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is tomorrow - * - * @example - * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow? - * var result = isTomorrow(new Date(2014, 9, 7, 14, 0)) - * //=> true - */ -function isTomorrow (dirtyDate) { - var tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 1); - return start_of_day(dirtyDate).getTime() === start_of_day(tomorrow).getTime() -} - -var is_tomorrow = isTomorrow; - -/** - * @category Weekday Helpers - * @summary Is the given date Tuesday? - * - * @description - * Is the given date Tuesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Tuesday - * - * @example - * // Is 23 September 2014 Tuesday? - * var result = isTuesday(new Date(2014, 8, 23)) - * //=> true - */ -function isTuesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 2 -} - -var is_tuesday = isTuesday; - -/** - * @category Weekday Helpers - * @summary Is the given date Wednesday? - * - * @description - * Is the given date Wednesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Wednesday - * - * @example - * // Is 24 September 2014 Wednesday? - * var result = isWednesday(new Date(2014, 8, 24)) - * //=> true - */ -function isWednesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 3 -} - -var is_wednesday = isWednesday; - -/** - * @category Weekday Helpers - * @summary Does the given date fall on a weekend? - * - * @description - * Does the given date fall on a weekend? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date falls on a weekend - * - * @example - * // Does 5 October 2014 fall on a weekend? - * var result = isWeekend(new Date(2014, 9, 5)) - * //=> true - */ -function isWeekend (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day === 0 || day === 6 -} - -var is_weekend = isWeekend; - -/** - * @category Range Helpers - * @summary Is the given date within the range? - * - * @description - * Is the given date within the range? - * - * @param {Date|String|Number} date - the date to check - * @param {Date|String|Number} startDate - the start of range - * @param {Date|String|Number} endDate - the end of range - * @returns {Boolean} the date is within the range - * @throws {Error} startDate cannot be after endDate - * - * @example - * // For the date within the range: - * isWithinRange( - * new Date(2014, 0, 3), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> true - * - * @example - * // For the date outside of the range: - * isWithinRange( - * new Date(2014, 0, 10), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> false - */ -function isWithinRange (dirtyDate, dirtyStartDate, dirtyEndDate) { - var time = parse_1(dirtyDate).getTime(); - var startTime = parse_1(dirtyStartDate).getTime(); - var endTime = parse_1(dirtyEndDate).getTime(); - - if (startTime > endTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return time >= startTime && time <= endTime -} - -var is_within_range = isWithinRange; - -/** - * @category Day Helpers - * @summary Is the given date yesterday? - * - * @description - * Is the given date yesterday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is yesterday - * - * @example - * // If today is 6 October 2014, is 5 October 14:00:00 yesterday? - * var result = isYesterday(new Date(2014, 9, 5, 14, 0)) - * //=> true - */ -function isYesterday (dirtyDate) { - var yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - return start_of_day(dirtyDate).getTime() === start_of_day(yesterday).getTime() -} - -var is_yesterday = isYesterday; - -/** - * @category Week Helpers - * @summary Return the last day of a week for the given date. - * - * @description - * Return the last day of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the last day of a week - * - * @example - * // The last day of a week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ -function lastDayOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setHours(0, 0, 0, 0); - date.setDate(date.getDate() + diff); - return date -} - -var last_day_of_week = lastDayOfWeek; - -/** - * @category ISO Week Helpers - * @summary Return the last day of an ISO week for the given date. - * - * @description - * Return the last day of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of an ISO week - * - * @example - * // The last day of an ISO week for 2 September 2014 11:55:00: - * var result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 00:00:00 - */ -function lastDayOfISOWeek (dirtyDate) { - return last_day_of_week(dirtyDate, {weekStartsOn: 1}) -} - -var last_day_of_iso_week = lastDayOfISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Return the last day of an ISO week-numbering year for the given date. - * - * @description - * Return the last day of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The last day of an ISO week-numbering year for 2 July 2005: - * var result = lastDayOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 00:00:00 - */ -function lastDayOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year + 1, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - date.setDate(date.getDate() - 1); - return date -} - -var last_day_of_iso_year = lastDayOfISOYear; - -/** - * @category Month Helpers - * @summary Return the last day of a month for the given date. - * - * @description - * Return the last day of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a month - * - * @example - * // The last day of a month for 2 September 2014 11:55:00: - * var result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ -function lastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(0, 0, 0, 0); - return date -} - -var last_day_of_month = lastDayOfMonth; - -/** - * @category Quarter Helpers - * @summary Return the last day of a year quarter for the given date. - * - * @description - * Return the last day of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a quarter - * - * @example - * // The last day of a quarter for 2 September 2014 11:55:00: - * var result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ -function lastDayOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(0, 0, 0, 0); - return date -} - -var last_day_of_quarter = lastDayOfQuarter; - -/** - * @category Year Helpers - * @summary Return the last day of a year for the given date. - * - * @description - * Return the last day of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a year - * - * @example - * // The last day of a year for 2 September 2014 11:55:00: - * var result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 00:00:00 - */ -function lastDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(0, 0, 0, 0); - return date -} - -var last_day_of_year = lastDayOfYear; - -/** - * @category Common Helpers - * @summary Return the latest of the given dates. - * - * @description - * Return the latest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the latest of the dates - * - * @example - * // Which of these dates is the latest? - * var result = max( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Sun Jul 02 1995 00:00:00 - */ -function max () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var latestTimestamp = Math.max.apply(null, dates); - return new Date(latestTimestamp) -} - -var max_1 = max; - -/** - * @category Common Helpers - * @summary Return the earliest of the given dates. - * - * @description - * Return the earliest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the earliest of the dates - * - * @example - * // Which of these dates is the earliest? - * var result = min( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Wed Feb 11 1987 00:00:00 - */ -function min () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var earliestTimestamp = Math.min.apply(null, dates); - return new Date(earliestTimestamp) -} - -var min_1 = min; - -/** - * @category Day Helpers - * @summary Set the day of the month to the given date. - * - * @description - * Set the day of the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfMonth - the day of the month of the new date - * @returns {Date} the new date with the day of the month setted - * - * @example - * // Set the 30th day of the month to 1 September 2014: - * var result = setDate(new Date(2014, 8, 1), 30) - * //=> Tue Sep 30 2014 00:00:00 - */ -function setDate (dirtyDate, dirtyDayOfMonth) { - var date = parse_1(dirtyDate); - var dayOfMonth = Number(dirtyDayOfMonth); - date.setDate(dayOfMonth); - return date -} - -var set_date = setDate; - -/** - * @category Weekday Helpers - * @summary Set the day of the week to the given date. - * - * @description - * Set the day of the week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the week of the new date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the new date with the day of the week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If week starts with Monday, set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0, {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ -function setDay (dirtyDate, dirtyDay, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = date.getDay(); - - var remainder = day % 7; - var dayIndex = (remainder + 7) % 7; - - var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; - return add_days(date, diff) -} - -var set_day = setDay; - -/** - * @category Day Helpers - * @summary Set the day of the year to the given date. - * - * @description - * Set the day of the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfYear - the day of the year of the new date - * @returns {Date} the new date with the day of the year setted - * - * @example - * // Set the 2nd day of the year to 2 July 2014: - * var result = setDayOfYear(new Date(2014, 6, 2), 2) - * //=> Thu Jan 02 2014 00:00:00 - */ -function setDayOfYear (dirtyDate, dirtyDayOfYear) { - var date = parse_1(dirtyDate); - var dayOfYear = Number(dirtyDayOfYear); - date.setMonth(0); - date.setDate(dayOfYear); - return date -} - -var set_day_of_year = setDayOfYear; - -/** - * @category Hour Helpers - * @summary Set the hours to the given date. - * - * @description - * Set the hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} hours - the hours of the new date - * @returns {Date} the new date with the hours setted - * - * @example - * // Set 4 hours to 1 September 2014 11:30:00: - * var result = setHours(new Date(2014, 8, 1, 11, 30), 4) - * //=> Mon Sep 01 2014 04:30:00 - */ -function setHours (dirtyDate, dirtyHours) { - var date = parse_1(dirtyDate); - var hours = Number(dirtyHours); - date.setHours(hours); - return date -} - -var set_hours = setHours; - -/** - * @category Weekday Helpers - * @summary Set the day of the ISO week to the given date. - * - * @description - * Set the day of the ISO week to the given date. - * ISO week starts with Monday. - * 7 is the index of Sunday, 1 is the index of Monday etc. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the ISO week of the new date - * @returns {Date} the new date with the day of the ISO week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setISODay(new Date(2014, 8, 1), 7) - * //=> Sun Sep 07 2014 00:00:00 - */ -function setISODay (dirtyDate, dirtyDay) { - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = get_iso_day(date); - var diff = day - currentDay; - return add_days(date, diff) -} - -var set_iso_day = setISODay; - -/** - * @category ISO Week Helpers - * @summary Set the ISO week to the given date. - * - * @description - * Set the ISO week to the given date, saving the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoWeek - the ISO week of the new date - * @returns {Date} the new date with the ISO week setted - * - * @example - * // Set the 53rd ISO week to 7 August 2004: - * var result = setISOWeek(new Date(2004, 7, 7), 53) - * //=> Sat Jan 01 2005 00:00:00 - */ -function setISOWeek (dirtyDate, dirtyISOWeek) { - var date = parse_1(dirtyDate); - var isoWeek = Number(dirtyISOWeek); - var diff = get_iso_week(date) - isoWeek; - date.setDate(date.getDate() - diff * 7); - return date -} - -var set_iso_week = setISOWeek; - -/** - * @category Millisecond Helpers - * @summary Set the milliseconds to the given date. - * - * @description - * Set the milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} milliseconds - the milliseconds of the new date - * @returns {Date} the new date with the milliseconds setted - * - * @example - * // Set 300 milliseconds to 1 September 2014 11:30:40.500: - * var result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300) - * //=> Mon Sep 01 2014 11:30:40.300 - */ -function setMilliseconds (dirtyDate, dirtyMilliseconds) { - var date = parse_1(dirtyDate); - var milliseconds = Number(dirtyMilliseconds); - date.setMilliseconds(milliseconds); - return date -} - -var set_milliseconds = setMilliseconds; - -/** - * @category Minute Helpers - * @summary Set the minutes to the given date. - * - * @description - * Set the minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} minutes - the minutes of the new date - * @returns {Date} the new date with the minutes setted - * - * @example - * // Set 45 minutes to 1 September 2014 11:30:40: - * var result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:45:40 - */ -function setMinutes (dirtyDate, dirtyMinutes) { - var date = parse_1(dirtyDate); - var minutes = Number(dirtyMinutes); - date.setMinutes(minutes); - return date -} - -var set_minutes = setMinutes; - -/** - * @category Month Helpers - * @summary Set the month to the given date. - * - * @description - * Set the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} month - the month of the new date - * @returns {Date} the new date with the month setted - * - * @example - * // Set February to 1 September 2014: - * var result = setMonth(new Date(2014, 8, 1), 1) - * //=> Sat Feb 01 2014 00:00:00 - */ -function setMonth (dirtyDate, dirtyMonth) { - var date = parse_1(dirtyDate); - var month = Number(dirtyMonth); - var year = date.getFullYear(); - var day = date.getDate(); - - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(year, month, 15); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(month, Math.min(day, daysInMonth)); - return date -} - -var set_month = setMonth; - -/** - * @category Quarter Helpers - * @summary Set the year quarter to the given date. - * - * @description - * Set the year quarter to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} quarter - the quarter of the new date - * @returns {Date} the new date with the quarter setted - * - * @example - * // Set the 2nd quarter to 2 July 2014: - * var result = setQuarter(new Date(2014, 6, 2), 2) - * //=> Wed Apr 02 2014 00:00:00 - */ -function setQuarter (dirtyDate, dirtyQuarter) { - var date = parse_1(dirtyDate); - var quarter = Number(dirtyQuarter); - var oldQuarter = Math.floor(date.getMonth() / 3) + 1; - var diff = quarter - oldQuarter; - return set_month(date, date.getMonth() + diff * 3) -} - -var set_quarter = setQuarter; - -/** - * @category Second Helpers - * @summary Set the seconds to the given date. - * - * @description - * Set the seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} seconds - the seconds of the new date - * @returns {Date} the new date with the seconds setted - * - * @example - * // Set 45 seconds to 1 September 2014 11:30:40: - * var result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:30:45 - */ -function setSeconds (dirtyDate, dirtySeconds) { - var date = parse_1(dirtyDate); - var seconds = Number(dirtySeconds); - date.setSeconds(seconds); - return date -} - -var set_seconds = setSeconds; - -/** - * @category Year Helpers - * @summary Set the year to the given date. - * - * @description - * Set the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} year - the year of the new date - * @returns {Date} the new date with the year setted - * - * @example - * // Set year 2013 to 1 September 2014: - * var result = setYear(new Date(2014, 8, 1), 2013) - * //=> Sun Sep 01 2013 00:00:00 - */ -function setYear (dirtyDate, dirtyYear) { - var date = parse_1(dirtyDate); - var year = Number(dirtyYear); - date.setFullYear(year); - return date -} - -var set_year = setYear; - -/** - * @category Month Helpers - * @summary Return the start of a month for the given date. - * - * @description - * Return the start of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a month - * - * @example - * // The start of a month for 2 September 2014 11:55:00: - * var result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ -function startOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - date.setDate(1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_month = startOfMonth; - -/** - * @category Day Helpers - * @summary Return the start of today. - * - * @description - * Return the start of today. - * - * @returns {Date} the start of today - * - * @example - * // If today is 6 October 2014: - * var result = startOfToday() - * //=> Mon Oct 6 2014 00:00:00 - */ -function startOfToday () { - return start_of_day(new Date()) -} - -var start_of_today = startOfToday; - -/** - * @category Day Helpers - * @summary Return the start of tomorrow. - * - * @description - * Return the start of tomorrow. - * - * @returns {Date} the start of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = startOfTomorrow() - * //=> Tue Oct 7 2014 00:00:00 - */ -function startOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_tomorrow = startOfTomorrow; - -/** - * @category Day Helpers - * @summary Return the start of yesterday. - * - * @description - * Return the start of yesterday. - * - * @returns {Date} the start of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = startOfYesterday() - * //=> Sun Oct 5 2014 00:00:00 - */ -function startOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_yesterday = startOfYesterday; - -/** - * @category Day Helpers - * @summary Subtract the specified number of days from the given date. - * - * @description - * Subtract the specified number of days from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be subtracted - * @returns {Date} the new date with the days subtracted - * - * @example - * // Subtract 10 days from 1 September 2014: - * var result = subDays(new Date(2014, 8, 1), 10) - * //=> Fri Aug 22 2014 00:00:00 - */ -function subDays (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_days(dirtyDate, -amount) -} - -var sub_days = subDays; - -/** - * @category Hour Helpers - * @summary Subtract the specified number of hours from the given date. - * - * @description - * Subtract the specified number of hours from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be subtracted - * @returns {Date} the new date with the hours subtracted - * - * @example - * // Subtract 2 hours from 11 July 2014 01:00:00: - * var result = subHours(new Date(2014, 6, 11, 1, 0), 2) - * //=> Thu Jul 10 2014 23:00:00 - */ -function subHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_hours(dirtyDate, -amount) -} - -var sub_hours = subHours; - -/** - * @category Millisecond Helpers - * @summary Subtract the specified number of milliseconds from the given date. - * - * @description - * Subtract the specified number of milliseconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be subtracted - * @returns {Date} the new date with the milliseconds subtracted - * - * @example - * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: - * var result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:29.250 - */ -function subMilliseconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, -amount) -} - -var sub_milliseconds = subMilliseconds; - -/** - * @category Minute Helpers - * @summary Subtract the specified number of minutes from the given date. - * - * @description - * Subtract the specified number of minutes from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be subtracted - * @returns {Date} the new date with the mintues subtracted - * - * @example - * // Subtract 30 minutes from 10 July 2014 12:00:00: - * var result = subMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 11:30:00 - */ -function subMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_minutes(dirtyDate, -amount) -} - -var sub_minutes = subMinutes; - -/** - * @category Month Helpers - * @summary Subtract the specified number of months from the given date. - * - * @description - * Subtract the specified number of months from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be subtracted - * @returns {Date} the new date with the months subtracted - * - * @example - * // Subtract 5 months from 1 February 2015: - * var result = subMonths(new Date(2015, 1, 1), 5) - * //=> Mon Sep 01 2014 00:00:00 - */ -function subMonths (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, -amount) -} - -var sub_months = subMonths; - -/** - * @category Quarter Helpers - * @summary Subtract the specified number of year quarters from the given date. - * - * @description - * Subtract the specified number of year quarters from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be subtracted - * @returns {Date} the new date with the quarters subtracted - * - * @example - * // Subtract 3 quarters from 1 September 2014: - * var result = subQuarters(new Date(2014, 8, 1), 3) - * //=> Sun Dec 01 2013 00:00:00 - */ -function subQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_quarters(dirtyDate, -amount) -} - -var sub_quarters = subQuarters; - -/** - * @category Second Helpers - * @summary Subtract the specified number of seconds from the given date. - * - * @description - * Subtract the specified number of seconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be subtracted - * @returns {Date} the new date with the seconds subtracted - * - * @example - * // Subtract 30 seconds from 10 July 2014 12:45:00: - * var result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:44:30 - */ -function subSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_seconds(dirtyDate, -amount) -} - -var sub_seconds = subSeconds; - -/** - * @category Week Helpers - * @summary Subtract the specified number of weeks from the given date. - * - * @description - * Subtract the specified number of weeks from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be subtracted - * @returns {Date} the new date with the weeks subtracted - * - * @example - * // Subtract 4 weeks from 1 September 2014: - * var result = subWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Aug 04 2014 00:00:00 - */ -function subWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_weeks(dirtyDate, -amount) -} - -var sub_weeks = subWeeks; - -/** - * @category Year Helpers - * @summary Subtract the specified number of years from the given date. - * - * @description - * Subtract the specified number of years from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be subtracted - * @returns {Date} the new date with the years subtracted - * - * @example - * // Subtract 5 years from 1 September 2014: - * var result = subYears(new Date(2014, 8, 1), 5) - * //=> Tue Sep 01 2009 00:00:00 - */ -function subYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_years(dirtyDate, -amount) -} - -var sub_years = subYears; - -var dateFns = { - addDays: add_days, - addHours: add_hours, - addISOYears: add_iso_years, - addMilliseconds: add_milliseconds, - addMinutes: add_minutes, - addMonths: add_months, - addQuarters: add_quarters, - addSeconds: add_seconds, - addWeeks: add_weeks, - addYears: add_years, - areRangesOverlapping: are_ranges_overlapping, - closestIndexTo: closest_index_to, - closestTo: closest_to, - compareAsc: compare_asc, - compareDesc: compare_desc, - differenceInCalendarDays: difference_in_calendar_days, - differenceInCalendarISOWeeks: difference_in_calendar_iso_weeks, - differenceInCalendarISOYears: difference_in_calendar_iso_years, - differenceInCalendarMonths: difference_in_calendar_months, - differenceInCalendarQuarters: difference_in_calendar_quarters, - differenceInCalendarWeeks: difference_in_calendar_weeks, - differenceInCalendarYears: difference_in_calendar_years, - differenceInDays: difference_in_days, - differenceInHours: difference_in_hours, - differenceInISOYears: difference_in_iso_years, - differenceInMilliseconds: difference_in_milliseconds, - differenceInMinutes: difference_in_minutes, - differenceInMonths: difference_in_months, - differenceInQuarters: difference_in_quarters, - differenceInSeconds: difference_in_seconds, - differenceInWeeks: difference_in_weeks, - differenceInYears: difference_in_years, - distanceInWords: distance_in_words, - distanceInWordsStrict: distance_in_words_strict, - distanceInWordsToNow: distance_in_words_to_now, - eachDay: each_day, - endOfDay: end_of_day, - endOfHour: end_of_hour, - endOfISOWeek: end_of_iso_week, - endOfISOYear: end_of_iso_year, - endOfMinute: end_of_minute, - endOfMonth: end_of_month, - endOfQuarter: end_of_quarter, - endOfSecond: end_of_second, - endOfToday: end_of_today, - endOfTomorrow: end_of_tomorrow, - endOfWeek: end_of_week, - endOfYear: end_of_year, - endOfYesterday: end_of_yesterday, - format: format_1, - getDate: get_date, - getDay: get_day, - getDayOfYear: get_day_of_year, - getDaysInMonth: get_days_in_month, - getDaysInYear: get_days_in_year, - getHours: get_hours, - getISODay: get_iso_day, - getISOWeek: get_iso_week, - getISOWeeksInYear: get_iso_weeks_in_year, - getISOYear: get_iso_year, - getMilliseconds: get_milliseconds, - getMinutes: get_minutes, - getMonth: get_month, - getOverlappingDaysInRanges: get_overlapping_days_in_ranges, - getQuarter: get_quarter, - getSeconds: get_seconds, - getTime: get_time, - getYear: get_year, - isAfter: is_after, - isBefore: is_before, - isDate: is_date, - isEqual: is_equal, - isFirstDayOfMonth: is_first_day_of_month, - isFriday: is_friday, - isFuture: is_future, - isLastDayOfMonth: is_last_day_of_month, - isLeapYear: is_leap_year, - isMonday: is_monday, - isPast: is_past, - isSameDay: is_same_day, - isSameHour: is_same_hour, - isSameISOWeek: is_same_iso_week, - isSameISOYear: is_same_iso_year, - isSameMinute: is_same_minute, - isSameMonth: is_same_month, - isSameQuarter: is_same_quarter, - isSameSecond: is_same_second, - isSameWeek: is_same_week, - isSameYear: is_same_year, - isSaturday: is_saturday, - isSunday: is_sunday, - isThisHour: is_this_hour, - isThisISOWeek: is_this_iso_week, - isThisISOYear: is_this_iso_year, - isThisMinute: is_this_minute, - isThisMonth: is_this_month, - isThisQuarter: is_this_quarter, - isThisSecond: is_this_second, - isThisWeek: is_this_week, - isThisYear: is_this_year, - isThursday: is_thursday, - isToday: is_today, - isTomorrow: is_tomorrow, - isTuesday: is_tuesday, - isValid: is_valid, - isWednesday: is_wednesday, - isWeekend: is_weekend, - isWithinRange: is_within_range, - isYesterday: is_yesterday, - lastDayOfISOWeek: last_day_of_iso_week, - lastDayOfISOYear: last_day_of_iso_year, - lastDayOfMonth: last_day_of_month, - lastDayOfQuarter: last_day_of_quarter, - lastDayOfWeek: last_day_of_week, - lastDayOfYear: last_day_of_year, - max: max_1, - min: min_1, - parse: parse_1, - setDate: set_date, - setDay: set_day, - setDayOfYear: set_day_of_year, - setHours: set_hours, - setISODay: set_iso_day, - setISOWeek: set_iso_week, - setISOYear: set_iso_year, - setMilliseconds: set_milliseconds, - setMinutes: set_minutes, - setMonth: set_month, - setQuarter: set_quarter, - setSeconds: set_seconds, - setYear: set_year, - startOfDay: start_of_day, - startOfHour: start_of_hour, - startOfISOWeek: start_of_iso_week, - startOfISOYear: start_of_iso_year, - startOfMinute: start_of_minute, - startOfMonth: start_of_month, - startOfQuarter: start_of_quarter, - startOfSecond: start_of_second, - startOfToday: start_of_today, - startOfTomorrow: start_of_tomorrow, - startOfWeek: start_of_week, - startOfYear: start_of_year, - startOfYesterday: start_of_yesterday, - subDays: sub_days, - subHours: sub_hours, - subISOYears: sub_iso_years, - subMilliseconds: sub_milliseconds, - subMinutes: sub_minutes, - subMonths: sub_months, - subQuarters: sub_quarters, - subSeconds: sub_seconds, - subWeeks: sub_weeks, - subYears: sub_years -}; - -const user = "user"; - -const date$2 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); -const foo$2 = `Sunnyvale ${user} ${date$2}`; - -const date$1 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); -const foo$1 = `@foo/lib/a ${date$1}`; - -const date = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); -const foo = `@foo/lib/a/a/a ${date}`; - -const fum = 'Wonderland'; - -var hello = 'Hello'; - -const name = 'Alice'; - -const json_key = "json_value"; - -console.log( - `${hello}, ${name} in ${fum} ${foo$2} ${foo$1} ${foo} ${far_a} ${far_a_b_c} ${json_key}`); - -// Test for sequences = false -class A { - a() { - return document.a; - } -} -function inline_me() { - return 'abc'; -} -console.error(new A().a(), inline_me(), some_global_var.thing); - -exports.A = A; -//# sourceMappingURL=bundle.cjs.js.map
diff --git a/packages/rollup/test/integration/golden.esm.js.map.sha256_ b/packages/rollup/test/integration/golden.esm.js.map.sha256_ deleted file mode 100644 index 83557aa..0000000 --- a/packages/rollup/test/integration/golden.esm.js.map.sha256_ +++ /dev/null
@@ -1 +0,0 @@ -a0ed85689082060843a42b518e03c7e64c656f6a6e05d34f3a466ba53816e27c \ No newline at end of file
diff --git a/packages/rollup/test/integration/golden.esm.js_ b/packages/rollup/test/integration/golden.esm.js_ deleted file mode 100644 index a0ffa8c..0000000 --- a/packages/rollup/test/integration/golden.esm.js_ +++ /dev/null
@@ -1,5678 +0,0 @@ -/** - * @license A dummy license banner that goes at the top of the file. - * This is version <unknown> - */ - -import { thing } from 'some_global_var'; - -var far_a = `@far/a`; - -var far_a_b_c = `@far/a/b/c`; - -var MILLISECONDS_IN_MINUTE$6 = 60000; - -/** - * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. - * They usually appear for dates that denote time before the timezones were introduced - * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 - * and GMT+01:00:00 after that date) - * - * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above, - * which would lead to incorrect calculations. - * - * This function returns the timezone offset in milliseconds that takes seconds in account. - */ -var getTimezoneOffsetInMilliseconds = function getTimezoneOffsetInMilliseconds (dirtyDate) { - var date = new Date(dirtyDate.getTime()); - var baseTimezoneOffset = date.getTimezoneOffset(); - date.setSeconds(0, 0); - var millisecondsPartOfTimezoneOffset = date.getTime() % MILLISECONDS_IN_MINUTE$6; - - return baseTimezoneOffset * MILLISECONDS_IN_MINUTE$6 + millisecondsPartOfTimezoneOffset -}; - -/** - * @category Common Helpers - * @summary Is the given argument an instance of Date? - * - * @description - * Is the given argument an instance of Date? - * - * @param {*} argument - the argument to check - * @returns {Boolean} the given argument is an instance of Date - * - * @example - * // Is 'mayonnaise' a Date? - * var result = isDate('mayonnaise') - * //=> false - */ -function isDate (argument) { - return argument instanceof Date -} - -var is_date = isDate; - -var MILLISECONDS_IN_HOUR$2 = 3600000; -var MILLISECONDS_IN_MINUTE$5 = 60000; -var DEFAULT_ADDITIONAL_DIGITS = 2; - -var parseTokenDateTimeDelimeter = /[T ]/; -var parseTokenPlainTime = /:/; - -// year tokens -var parseTokenYY = /^(\d{2})$/; -var parseTokensYYY = [ - /^([+-]\d{2})$/, // 0 additional digits - /^([+-]\d{3})$/, // 1 additional digit - /^([+-]\d{4})$/ // 2 additional digits -]; - -var parseTokenYYYY = /^(\d{4})/; -var parseTokensYYYYY = [ - /^([+-]\d{4})/, // 0 additional digits - /^([+-]\d{5})/, // 1 additional digit - /^([+-]\d{6})/ // 2 additional digits -]; - -// date tokens -var parseTokenMM = /^-(\d{2})$/; -var parseTokenDDD = /^-?(\d{3})$/; -var parseTokenMMDD = /^-?(\d{2})-?(\d{2})$/; -var parseTokenWww = /^-?W(\d{2})$/; -var parseTokenWwwD = /^-?W(\d{2})-?(\d{1})$/; - -// time tokens -var parseTokenHH = /^(\d{2}([.,]\d*)?)$/; -var parseTokenHHMM = /^(\d{2}):?(\d{2}([.,]\d*)?)$/; -var parseTokenHHMMSS = /^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/; - -// timezone tokens -var parseTokenTimezone = /([Z+-].*)$/; -var parseTokenTimezoneZ = /^(Z)$/; -var parseTokenTimezoneHH = /^([+-])(\d{2})$/; -var parseTokenTimezoneHHMM = /^([+-])(\d{2}):?(\d{2})$/; - -/** - * @category Common Helpers - * @summary Convert the given argument to an instance of Date. - * - * @description - * Convert the given argument to an instance of Date. - * - * If the argument is an instance of Date, the function returns its clone. - * - * If the argument is a number, it is treated as a timestamp. - * - * If an argument is a string, the function tries to parse it. - * Function accepts complete ISO 8601 formats as well as partial implementations. - * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 - * - * If all above fails, the function passes the given argument to Date constructor. - * - * @param {Date|String|Number} argument - the value to convert - * @param {Object} [options] - the object with options - * @param {0 | 1 | 2} [options.additionalDigits=2] - the additional number of digits in the extended year format - * @returns {Date} the parsed date in the local time zone - * - * @example - * // Convert string '2014-02-11T11:30:30' to date: - * var result = parse('2014-02-11T11:30:30') - * //=> Tue Feb 11 2014 11:30:30 - * - * @example - * // Parse string '+02014101', - * // if the additional number of digits in the extended year format is 1: - * var result = parse('+02014101', {additionalDigits: 1}) - * //=> Fri Apr 11 2014 00:00:00 - */ -function parse (argument, dirtyOptions) { - if (is_date(argument)) { - // Prevent the date to lose the milliseconds when passed to new Date() in IE10 - return new Date(argument.getTime()) - } else if (typeof argument !== 'string') { - return new Date(argument) - } - - var options = dirtyOptions || {}; - var additionalDigits = options.additionalDigits; - if (additionalDigits == null) { - additionalDigits = DEFAULT_ADDITIONAL_DIGITS; - } else { - additionalDigits = Number(additionalDigits); - } - - var dateStrings = splitDateString(argument); - - var parseYearResult = parseYear(dateStrings.date, additionalDigits); - var year = parseYearResult.year; - var restDateString = parseYearResult.restDateString; - - var date = parseDate(restDateString, year); - - if (date) { - var timestamp = date.getTime(); - var time = 0; - var offset; - - if (dateStrings.time) { - time = parseTime(dateStrings.time); - } - - if (dateStrings.timezone) { - offset = parseTimezone(dateStrings.timezone) * MILLISECONDS_IN_MINUTE$5; - } else { - var fullTime = timestamp + time; - var fullTimeDate = new Date(fullTime); - - offset = getTimezoneOffsetInMilliseconds(fullTimeDate); - - // Adjust time when it's coming from DST - var fullTimeDateNextDay = new Date(fullTime); - fullTimeDateNextDay.setDate(fullTimeDate.getDate() + 1); - var offsetDiff = - getTimezoneOffsetInMilliseconds(fullTimeDateNextDay) - - getTimezoneOffsetInMilliseconds(fullTimeDate); - if (offsetDiff > 0) { - offset += offsetDiff; - } - } - - return new Date(timestamp + time + offset) - } else { - return new Date(argument) - } -} - -function splitDateString (dateString) { - var dateStrings = {}; - var array = dateString.split(parseTokenDateTimeDelimeter); - var timeString; - - if (parseTokenPlainTime.test(array[0])) { - dateStrings.date = null; - timeString = array[0]; - } else { - dateStrings.date = array[0]; - timeString = array[1]; - } - - if (timeString) { - var token = parseTokenTimezone.exec(timeString); - if (token) { - dateStrings.time = timeString.replace(token[1], ''); - dateStrings.timezone = token[1]; - } else { - dateStrings.time = timeString; - } - } - - return dateStrings -} - -function parseYear (dateString, additionalDigits) { - var parseTokenYYY = parseTokensYYY[additionalDigits]; - var parseTokenYYYYY = parseTokensYYYYY[additionalDigits]; - - var token; - - // YYYY or ±YYYYY - token = parseTokenYYYY.exec(dateString) || parseTokenYYYYY.exec(dateString); - if (token) { - var yearString = token[1]; - return { - year: parseInt(yearString, 10), - restDateString: dateString.slice(yearString.length) - } - } - - // YY or ±YYY - token = parseTokenYY.exec(dateString) || parseTokenYYY.exec(dateString); - if (token) { - var centuryString = token[1]; - return { - year: parseInt(centuryString, 10) * 100, - restDateString: dateString.slice(centuryString.length) - } - } - - // Invalid ISO-formatted year - return { - year: null - } -} - -function parseDate (dateString, year) { - // Invalid ISO-formatted year - if (year === null) { - return null - } - - var token; - var date; - var month; - var week; - - // YYYY - if (dateString.length === 0) { - date = new Date(0); - date.setUTCFullYear(year); - return date - } - - // YYYY-MM - token = parseTokenMM.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - date.setUTCFullYear(year, month); - return date - } - - // YYYY-DDD or YYYYDDD - token = parseTokenDDD.exec(dateString); - if (token) { - date = new Date(0); - var dayOfYear = parseInt(token[1], 10); - date.setUTCFullYear(year, 0, dayOfYear); - return date - } - - // YYYY-MM-DD or YYYYMMDD - token = parseTokenMMDD.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - var day = parseInt(token[2], 10); - date.setUTCFullYear(year, month, day); - return date - } - - // YYYY-Www or YYYYWww - token = parseTokenWww.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - return dayOfISOYear(year, week) - } - - // YYYY-Www-D or YYYYWwwD - token = parseTokenWwwD.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - var dayOfWeek = parseInt(token[2], 10) - 1; - return dayOfISOYear(year, week, dayOfWeek) - } - - // Invalid ISO-formatted date - return null -} - -function parseTime (timeString) { - var token; - var hours; - var minutes; - - // hh - token = parseTokenHH.exec(timeString); - if (token) { - hours = parseFloat(token[1].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 - } - - // hh:mm or hhmm - token = parseTokenHHMM.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseFloat(token[2].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 - } - - // hh:mm:ss or hhmmss - token = parseTokenHHMMSS.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseInt(token[2], 10); - var seconds = parseFloat(token[3].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 + - seconds * 1000 - } - - // Invalid ISO-formatted time - return null -} - -function parseTimezone (timezoneString) { - var token; - var absoluteOffset; - - // Z - token = parseTokenTimezoneZ.exec(timezoneString); - if (token) { - return 0 - } - - // ±hh - token = parseTokenTimezoneHH.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60; - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - // ±hh:mm or ±hhmm - token = parseTokenTimezoneHHMM.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60 + parseInt(token[3], 10); - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - return 0 -} - -function dayOfISOYear (isoYear, week, day) { - week = week || 0; - day = day || 0; - var date = new Date(0); - date.setUTCFullYear(isoYear, 0, 4); - var fourthOfJanuaryDay = date.getUTCDay() || 7; - var diff = week * 7 + day + 1 - fourthOfJanuaryDay; - date.setUTCDate(date.getUTCDate() + diff); - return date -} - -var parse_1 = parse; - -/** - * @category Day Helpers - * @summary Add the specified number of days to the given date. - * - * @description - * Add the specified number of days to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be added - * @returns {Date} the new date with the days added - * - * @example - * // Add 10 days to 1 September 2014: - * var result = addDays(new Date(2014, 8, 1), 10) - * //=> Thu Sep 11 2014 00:00:00 - */ -function addDays (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - date.setDate(date.getDate() + amount); - return date -} - -var add_days = addDays; - -/** - * @category Millisecond Helpers - * @summary Add the specified number of milliseconds to the given date. - * - * @description - * Add the specified number of milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be added - * @returns {Date} the new date with the milliseconds added - * - * @example - * // Add 750 milliseconds to 10 July 2014 12:45:30.000: - * var result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:30.750 - */ -function addMilliseconds (dirtyDate, dirtyAmount) { - var timestamp = parse_1(dirtyDate).getTime(); - var amount = Number(dirtyAmount); - return new Date(timestamp + amount) -} - -var add_milliseconds = addMilliseconds; - -var MILLISECONDS_IN_HOUR$1 = 3600000; - -/** - * @category Hour Helpers - * @summary Add the specified number of hours to the given date. - * - * @description - * Add the specified number of hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be added - * @returns {Date} the new date with the hours added - * - * @example - * // Add 2 hours to 10 July 2014 23:00:00: - * var result = addHours(new Date(2014, 6, 10, 23, 0), 2) - * //=> Fri Jul 11 2014 01:00:00 - */ -function addHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR$1) -} - -var add_hours = addHours; - -/** - * @category Week Helpers - * @summary Return the start of a week for the given date. - * - * @description - * Return the start of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the start of a week - * - * @example - * // The start of a week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Mon Sep 01 2014 00:00:00 - */ -function startOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - - date.setDate(date.getDate() - diff); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_week = startOfWeek; - -/** - * @category ISO Week Helpers - * @summary Return the start of an ISO week for the given date. - * - * @description - * Return the start of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO week - * - * @example - * // The start of an ISO week for 2 September 2014 11:55:00: - * var result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ -function startOfISOWeek (dirtyDate) { - return start_of_week(dirtyDate, {weekStartsOn: 1}) -} - -var start_of_iso_week = startOfISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Get the ISO week-numbering year of the given date. - * - * @description - * Get the ISO week-numbering year of the given date, - * which always starts 3 days before the year's first Thursday. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week-numbering year - * - * @example - * // Which ISO-week numbering year is 2 January 2005? - * var result = getISOYear(new Date(2005, 0, 2)) - * //=> 2004 - */ -function getISOYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var startOfNextYear = start_of_iso_week(fourthOfJanuaryOfNextYear); - - var fourthOfJanuaryOfThisYear = new Date(0); - fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); - fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); - var startOfThisYear = start_of_iso_week(fourthOfJanuaryOfThisYear); - - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1 - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year - } else { - return year - 1 - } -} - -var get_iso_year = getISOYear; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Return the start of an ISO week-numbering year for the given date. - * - * @description - * Return the start of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO year - * - * @example - * // The start of an ISO week-numbering year for 2 July 2005: - * var result = startOfISOYear(new Date(2005, 6, 2)) - * //=> Mon Jan 03 2005 00:00:00 - */ -function startOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - return date -} - -var start_of_iso_year = startOfISOYear; - -/** - * @category Day Helpers - * @summary Return the start of a day for the given date. - * - * @description - * Return the start of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a day - * - * @example - * // The start of a day for 2 September 2014 11:55:00: - * var result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 00:00:00 - */ -function startOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_day = startOfDay; - -var MILLISECONDS_IN_MINUTE$4 = 60000; -var MILLISECONDS_IN_DAY$1 = 86400000; - -/** - * @category Day Helpers - * @summary Get the number of calendar days between the given dates. - * - * @description - * Get the number of calendar days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar days - * - * @example - * // How many calendar days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInCalendarDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 366 - */ -function differenceInCalendarDays (dirtyDateLeft, dirtyDateRight) { - var startOfDayLeft = start_of_day(dirtyDateLeft); - var startOfDayRight = start_of_day(dirtyDateRight); - - var timestampLeft = startOfDayLeft.getTime() - - startOfDayLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - var timestampRight = startOfDayRight.getTime() - - startOfDayRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a day is not constant - // (e.g. it's different in the day of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY$1) -} - -var difference_in_calendar_days = differenceInCalendarDays; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Set the ISO week-numbering year to the given date. - * - * @description - * Set the ISO week-numbering year to the given date, - * saving the week number and the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoYear - the ISO week-numbering year of the new date - * @returns {Date} the new date with the ISO week-numbering year setted - * - * @example - * // Set ISO week-numbering year 2007 to 29 December 2008: - * var result = setISOYear(new Date(2008, 11, 29), 2007) - * //=> Mon Jan 01 2007 00:00:00 - */ -function setISOYear (dirtyDate, dirtyISOYear) { - var date = parse_1(dirtyDate); - var isoYear = Number(dirtyISOYear); - var diff = difference_in_calendar_days(date, start_of_iso_year(date)); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(isoYear, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - date = start_of_iso_year(fourthOfJanuary); - date.setDate(date.getDate() + diff); - return date -} - -var set_iso_year = setISOYear; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Add the specified number of ISO week-numbering years to the given date. - * - * @description - * Add the specified number of ISO week-numbering years to the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be added - * @returns {Date} the new date with the ISO week-numbering years added - * - * @example - * // Add 5 ISO week-numbering years to 2 July 2010: - * var result = addISOYears(new Date(2010, 6, 2), 5) - * //=> Fri Jun 26 2015 00:00:00 - */ -function addISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return set_iso_year(dirtyDate, get_iso_year(dirtyDate) + amount) -} - -var add_iso_years = addISOYears; - -var MILLISECONDS_IN_MINUTE$3 = 60000; - -/** - * @category Minute Helpers - * @summary Add the specified number of minutes to the given date. - * - * @description - * Add the specified number of minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be added - * @returns {Date} the new date with the minutes added - * - * @example - * // Add 30 minutes to 10 July 2014 12:00:00: - * var result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 12:30:00 - */ -function addMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE$3) -} - -var add_minutes = addMinutes; - -/** - * @category Month Helpers - * @summary Get the number of days in a month of the given date. - * - * @description - * Get the number of days in a month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a month - * - * @example - * // How many days are in February 2000? - * var result = getDaysInMonth(new Date(2000, 1)) - * //=> 29 - */ -function getDaysInMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - var monthIndex = date.getMonth(); - var lastDayOfMonth = new Date(0); - lastDayOfMonth.setFullYear(year, monthIndex + 1, 0); - lastDayOfMonth.setHours(0, 0, 0, 0); - return lastDayOfMonth.getDate() -} - -var get_days_in_month = getDaysInMonth; - -/** - * @category Month Helpers - * @summary Add the specified number of months to the given date. - * - * @description - * Add the specified number of months to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be added - * @returns {Date} the new date with the months added - * - * @example - * // Add 5 months to 1 September 2014: - * var result = addMonths(new Date(2014, 8, 1), 5) - * //=> Sun Feb 01 2015 00:00:00 - */ -function addMonths (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - var desiredMonth = date.getMonth() + amount; - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(date.getFullYear(), desiredMonth, 1); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(desiredMonth, Math.min(daysInMonth, date.getDate())); - return date -} - -var add_months = addMonths; - -/** - * @category Quarter Helpers - * @summary Add the specified number of year quarters to the given date. - * - * @description - * Add the specified number of year quarters to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be added - * @returns {Date} the new date with the quarters added - * - * @example - * // Add 1 quarter to 1 September 2014: - * var result = addQuarters(new Date(2014, 8, 1), 1) - * //=> Mon Dec 01 2014 00:00:00 - */ -function addQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var months = amount * 3; - return add_months(dirtyDate, months) -} - -var add_quarters = addQuarters; - -/** - * @category Second Helpers - * @summary Add the specified number of seconds to the given date. - * - * @description - * Add the specified number of seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be added - * @returns {Date} the new date with the seconds added - * - * @example - * // Add 30 seconds to 10 July 2014 12:45:00: - * var result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:45:30 - */ -function addSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * 1000) -} - -var add_seconds = addSeconds; - -/** - * @category Week Helpers - * @summary Add the specified number of weeks to the given date. - * - * @description - * Add the specified number of week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be added - * @returns {Date} the new date with the weeks added - * - * @example - * // Add 4 weeks to 1 September 2014: - * var result = addWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Sep 29 2014 00:00:00 - */ -function addWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var days = amount * 7; - return add_days(dirtyDate, days) -} - -var add_weeks = addWeeks; - -/** - * @category Year Helpers - * @summary Add the specified number of years to the given date. - * - * @description - * Add the specified number of years to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be added - * @returns {Date} the new date with the years added - * - * @example - * // Add 5 years to 1 September 2014: - * var result = addYears(new Date(2014, 8, 1), 5) - * //=> Sun Sep 01 2019 00:00:00 - */ -function addYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, amount * 12) -} - -var add_years = addYears; - -/** - * @category Range Helpers - * @summary Is the given date range overlapping with another date range? - * - * @description - * Is the given date range overlapping with another date range? - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Boolean} whether the date ranges are overlapping - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> true - * - * @example - * // For non-overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> false - */ -function areRangesOverlapping (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return initialStartTime < comparedEndTime && comparedStartTime < initialEndTime -} - -var are_ranges_overlapping = areRangesOverlapping; - -/** - * @category Common Helpers - * @summary Return an index of the closest date from the array comparing to the given date. - * - * @description - * Return an index of the closest date from the array comparing to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Number} an index of the date closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015? - * var dateToCompare = new Date(2015, 8, 6) - * var datesArray = [ - * new Date(2015, 0, 1), - * new Date(2016, 0, 1), - * new Date(2017, 0, 1) - * ] - * var result = closestIndexTo(dateToCompare, datesArray) - * //=> 1 - */ -function closestIndexTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate, index) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = index; - minDistance = distance; - } - }); - - return result -} - -var closest_index_to = closestIndexTo; - -/** - * @category Common Helpers - * @summary Return a date from the array closest to the given date. - * - * @description - * Return a date from the array closest to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Date} the date from the array closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030? - * var dateToCompare = new Date(2015, 8, 6) - * var result = closestTo(dateToCompare, [ - * new Date(2000, 0, 1), - * new Date(2030, 0, 1) - * ]) - * //=> Tue Jan 01 2030 00:00:00 - */ -function closestTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = currentDate; - minDistance = distance; - } - }); - - return result -} - -var closest_to = closestTo; - -/** - * @category Common Helpers - * @summary Compare the two dates and return -1, 0 or 1. - * - * @description - * Compare the two dates and return 1 if the first date is after the second, - * -1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989: - * var result = compareAsc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> -1 - * - * @example - * // Sort the array of dates: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareAsc) - * //=> [ - * // Wed Feb 11 1987 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Sun Jul 02 1995 00:00:00 - * // ] - */ -function compareAsc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft < timeRight) { - return -1 - } else if (timeLeft > timeRight) { - return 1 - } else { - return 0 - } -} - -var compare_asc = compareAsc; - -/** - * @category Common Helpers - * @summary Compare the two dates reverse chronologically and return -1, 0 or 1. - * - * @description - * Compare the two dates and return -1 if the first date is after the second, - * 1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989 reverse chronologically: - * var result = compareDesc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> 1 - * - * @example - * // Sort the array of dates in reverse chronological order: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareDesc) - * //=> [ - * // Sun Jul 02 1995 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Wed Feb 11 1987 00:00:00 - * // ] - */ -function compareDesc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft > timeRight) { - return -1 - } else if (timeLeft < timeRight) { - return 1 - } else { - return 0 - } -} - -var compare_desc = compareDesc; - -var MILLISECONDS_IN_MINUTE$2 = 60000; -var MILLISECONDS_IN_WEEK$3 = 604800000; - -/** - * @category ISO Week Helpers - * @summary Get the number of calendar ISO weeks between the given dates. - * - * @description - * Get the number of calendar ISO weeks between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO weeks - * - * @example - * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014? - * var result = differenceInCalendarISOWeeks( - * new Date(2014, 6, 21), - * new Date(2014, 6, 6) - * ) - * //=> 3 - */ -function differenceInCalendarISOWeeks (dirtyDateLeft, dirtyDateRight) { - var startOfISOWeekLeft = start_of_iso_week(dirtyDateLeft); - var startOfISOWeekRight = start_of_iso_week(dirtyDateRight); - - var timestampLeft = startOfISOWeekLeft.getTime() - - startOfISOWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - var timestampRight = startOfISOWeekRight.getTime() - - startOfISOWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$3) -} - -var difference_in_calendar_iso_weeks = differenceInCalendarISOWeeks; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of calendar ISO week-numbering years between the given dates. - * - * @description - * Get the number of calendar ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO week-numbering years - * - * @example - * // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012? - * var result = differenceInCalendarISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 2 - */ -function differenceInCalendarISOYears (dirtyDateLeft, dirtyDateRight) { - return get_iso_year(dirtyDateLeft) - get_iso_year(dirtyDateRight) -} - -var difference_in_calendar_iso_years = differenceInCalendarISOYears; - -/** - * @category Month Helpers - * @summary Get the number of calendar months between the given dates. - * - * @description - * Get the number of calendar months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar months - * - * @example - * // How many calendar months are between 31 January 2014 and 1 September 2014? - * var result = differenceInCalendarMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 8 - */ -function differenceInCalendarMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); - - return yearDiff * 12 + monthDiff -} - -var difference_in_calendar_months = differenceInCalendarMonths; - -/** - * @category Quarter Helpers - * @summary Get the year quarter of the given date. - * - * @description - * Get the year quarter of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the quarter - * - * @example - * // Which quarter is 2 July 2014? - * var result = getQuarter(new Date(2014, 6, 2)) - * //=> 3 - */ -function getQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var quarter = Math.floor(date.getMonth() / 3) + 1; - return quarter -} - -var get_quarter = getQuarter; - -/** - * @category Quarter Helpers - * @summary Get the number of calendar quarters between the given dates. - * - * @description - * Get the number of calendar quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar quarters - * - * @example - * // How many calendar quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInCalendarQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 3 - */ -function differenceInCalendarQuarters (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var quarterDiff = get_quarter(dateLeft) - get_quarter(dateRight); - - return yearDiff * 4 + quarterDiff -} - -var difference_in_calendar_quarters = differenceInCalendarQuarters; - -var MILLISECONDS_IN_MINUTE$1 = 60000; -var MILLISECONDS_IN_WEEK$2 = 604800000; - -/** - * @category Week Helpers - * @summary Get the number of calendar weeks between the given dates. - * - * @description - * Get the number of calendar weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Number} the number of calendar weeks - * - * @example - * // How many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 3 - * - * @example - * // If the week starts on Monday, - * // how many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5), - * {weekStartsOn: 1} - * ) - * //=> 2 - */ -function differenceInCalendarWeeks (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var startOfWeekLeft = start_of_week(dirtyDateLeft, dirtyOptions); - var startOfWeekRight = start_of_week(dirtyDateRight, dirtyOptions); - - var timestampLeft = startOfWeekLeft.getTime() - - startOfWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - var timestampRight = startOfWeekRight.getTime() - - startOfWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$2) -} - -var difference_in_calendar_weeks = differenceInCalendarWeeks; - -/** - * @category Year Helpers - * @summary Get the number of calendar years between the given dates. - * - * @description - * Get the number of calendar years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar years - * - * @example - * // How many calendar years are between 31 December 2013 and 11 February 2015? - * var result = differenceInCalendarYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ -function differenceInCalendarYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - return dateLeft.getFullYear() - dateRight.getFullYear() -} - -var difference_in_calendar_years = differenceInCalendarYears; - -/** - * @category Day Helpers - * @summary Get the number of full days between the given dates. - * - * @description - * Get the number of full days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full days - * - * @example - * // How many full days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 365 - */ -function differenceInDays (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_days(dateLeft, dateRight)); - dateLeft.setDate(dateLeft.getDate() - sign * difference); - - // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full - // If so, result must be decreased by 1 in absolute value - var isLastDayNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastDayNotFull) -} - -var difference_in_days = differenceInDays; - -/** - * @category Millisecond Helpers - * @summary Get the number of milliseconds between the given dates. - * - * @description - * Get the number of milliseconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of milliseconds - * - * @example - * // How many milliseconds are between - * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700? - * var result = differenceInMilliseconds( - * new Date(2014, 6, 2, 12, 30, 21, 700), - * new Date(2014, 6, 2, 12, 30, 20, 600) - * ) - * //=> 1100 - */ -function differenceInMilliseconds (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getTime() - dateRight.getTime() -} - -var difference_in_milliseconds = differenceInMilliseconds; - -var MILLISECONDS_IN_HOUR = 3600000; - -/** - * @category Hour Helpers - * @summary Get the number of hours between the given dates. - * - * @description - * Get the number of hours between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of hours - * - * @example - * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00? - * var result = differenceInHours( - * new Date(2014, 6, 2, 19, 0), - * new Date(2014, 6, 2, 6, 50) - * ) - * //=> 12 - */ -function differenceInHours (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_hours = differenceInHours; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Subtract the specified number of ISO week-numbering years from the given date. - * - * @description - * Subtract the specified number of ISO week-numbering years from the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be subtracted - * @returns {Date} the new date with the ISO week-numbering years subtracted - * - * @example - * // Subtract 5 ISO week-numbering years from 1 September 2014: - * var result = subISOYears(new Date(2014, 8, 1), 5) - * //=> Mon Aug 31 2009 00:00:00 - */ -function subISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_iso_years(dirtyDate, -amount) -} - -var sub_iso_years = subISOYears; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of full ISO week-numbering years between the given dates. - * - * @description - * Get the number of full ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full ISO week-numbering years - * - * @example - * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012? - * var result = differenceInISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 1 - */ -function differenceInISOYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_iso_years(dateLeft, dateRight)); - dateLeft = sub_iso_years(dateLeft, sign * difference); - - // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1 - // if last calendar ISO year is not full - // If so, result must be decreased by 1 in absolute value - var isLastISOYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastISOYearNotFull) -} - -var difference_in_iso_years = differenceInISOYears; - -var MILLISECONDS_IN_MINUTE = 60000; - -/** - * @category Minute Helpers - * @summary Get the number of minutes between the given dates. - * - * @description - * Get the number of minutes between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of minutes - * - * @example - * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00? - * var result = differenceInMinutes( - * new Date(2014, 6, 2, 12, 20, 0), - * new Date(2014, 6, 2, 12, 7, 59) - * ) - * //=> 12 - */ -function differenceInMinutes (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_minutes = differenceInMinutes; - -/** - * @category Month Helpers - * @summary Get the number of full months between the given dates. - * - * @description - * Get the number of full months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full months - * - * @example - * // How many full months are between 31 January 2014 and 1 September 2014? - * var result = differenceInMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 7 - */ -function differenceInMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_months(dateLeft, dateRight)); - dateLeft.setMonth(dateLeft.getMonth() - sign * difference); - - // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full - // If so, result must be decreased by 1 in absolute value - var isLastMonthNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastMonthNotFull) -} - -var difference_in_months = differenceInMonths; - -/** - * @category Quarter Helpers - * @summary Get the number of full quarters between the given dates. - * - * @description - * Get the number of full quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full quarters - * - * @example - * // How many full quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ -function differenceInQuarters (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_months(dirtyDateLeft, dirtyDateRight) / 3; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_quarters = differenceInQuarters; - -/** - * @category Second Helpers - * @summary Get the number of seconds between the given dates. - * - * @description - * Get the number of seconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of seconds - * - * @example - * // How many seconds are between - * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000? - * var result = differenceInSeconds( - * new Date(2014, 6, 2, 12, 30, 20, 0), - * new Date(2014, 6, 2, 12, 30, 7, 999) - * ) - * //=> 12 - */ -function differenceInSeconds (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / 1000; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_seconds = differenceInSeconds; - -/** - * @category Week Helpers - * @summary Get the number of full weeks between the given dates. - * - * @description - * Get the number of full weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full weeks - * - * @example - * // How many full weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 2 - */ -function differenceInWeeks (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_days(dirtyDateLeft, dirtyDateRight) / 7; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) -} - -var difference_in_weeks = differenceInWeeks; - -/** - * @category Year Helpers - * @summary Get the number of full years between the given dates. - * - * @description - * Get the number of full years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full years - * - * @example - * // How many full years are between 31 December 2013 and 11 February 2015? - * var result = differenceInYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 1 - */ -function differenceInYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_years(dateLeft, dateRight)); - dateLeft.setFullYear(dateLeft.getFullYear() - sign * difference); - - // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full - // If so, result must be decreased by 1 in absolute value - var isLastYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastYearNotFull) -} - -var difference_in_years = differenceInYears; - -function buildDistanceInWordsLocale () { - var distanceInWordsLocale = { - lessThanXSeconds: { - one: 'less than a second', - other: 'less than {{count}} seconds' - }, - - xSeconds: { - one: '1 second', - other: '{{count}} seconds' - }, - - halfAMinute: 'half a minute', - - lessThanXMinutes: { - one: 'less than a minute', - other: 'less than {{count}} minutes' - }, - - xMinutes: { - one: '1 minute', - other: '{{count}} minutes' - }, - - aboutXHours: { - one: 'about 1 hour', - other: 'about {{count}} hours' - }, - - xHours: { - one: '1 hour', - other: '{{count}} hours' - }, - - xDays: { - one: '1 day', - other: '{{count}} days' - }, - - aboutXMonths: { - one: 'about 1 month', - other: 'about {{count}} months' - }, - - xMonths: { - one: '1 month', - other: '{{count}} months' - }, - - aboutXYears: { - one: 'about 1 year', - other: 'about {{count}} years' - }, - - xYears: { - one: '1 year', - other: '{{count}} years' - }, - - overXYears: { - one: 'over 1 year', - other: 'over {{count}} years' - }, - - almostXYears: { - one: 'almost 1 year', - other: 'almost {{count}} years' - } - }; - - function localize (token, count, options) { - options = options || {}; - - var result; - if (typeof distanceInWordsLocale[token] === 'string') { - result = distanceInWordsLocale[token]; - } else if (count === 1) { - result = distanceInWordsLocale[token].one; - } else { - result = distanceInWordsLocale[token].other.replace('{{count}}', count); - } - - if (options.addSuffix) { - if (options.comparison > 0) { - return 'in ' + result - } else { - return result + ' ago' - } - } - - return result - } - - return { - localize: localize - } -} - -var build_distance_in_words_locale = buildDistanceInWordsLocale; - -var commonFormatterKeys = [ - 'M', 'MM', 'Q', 'D', 'DD', 'DDD', 'DDDD', 'd', - 'E', 'W', 'WW', 'YY', 'YYYY', 'GG', 'GGGG', - 'H', 'HH', 'h', 'hh', 'm', 'mm', - 's', 'ss', 'S', 'SS', 'SSS', - 'Z', 'ZZ', 'X', 'x' -]; - -function buildFormattingTokensRegExp (formatters) { - var formatterKeys = []; - for (var key in formatters) { - if (formatters.hasOwnProperty(key)) { - formatterKeys.push(key); - } - } - - var formattingTokens = commonFormatterKeys - .concat(formatterKeys) - .sort() - .reverse(); - var formattingTokensRegExp = new RegExp( - '(\\[[^\\[]*\\])|(\\\\)?' + '(' + formattingTokens.join('|') + '|.)', 'g' - ); - - return formattingTokensRegExp -} - -var build_formatting_tokens_reg_exp = buildFormattingTokensRegExp; - -function buildFormatLocale () { - // Note: in English, the names of days of the week and months are capitalized. - // If you are making a new locale based on this one, check if the same is true for the language you're working on. - // Generally, formatted dates should look like they are in the middle of a sentence, - // e.g. in Spanish language the weekdays and months should be in the lowercase. - var months3char = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var monthsFull = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; - var weekdays2char = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']; - var weekdays3char = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - var weekdaysFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; - var meridiemUppercase = ['AM', 'PM']; - var meridiemLowercase = ['am', 'pm']; - var meridiemFull = ['a.m.', 'p.m.']; - - var formatters = { - // Month: Jan, Feb, ..., Dec - 'MMM': function (date) { - return months3char[date.getMonth()] - }, - - // Month: January, February, ..., December - 'MMMM': function (date) { - return monthsFull[date.getMonth()] - }, - - // Day of week: Su, Mo, ..., Sa - 'dd': function (date) { - return weekdays2char[date.getDay()] - }, - - // Day of week: Sun, Mon, ..., Sat - 'ddd': function (date) { - return weekdays3char[date.getDay()] - }, - - // Day of week: Sunday, Monday, ..., Saturday - 'dddd': function (date) { - return weekdaysFull[date.getDay()] - }, - - // AM, PM - 'A': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemUppercase[1] : meridiemUppercase[0] - }, - - // am, pm - 'a': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemLowercase[1] : meridiemLowercase[0] - }, - - // a.m., p.m. - 'aa': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemFull[1] : meridiemFull[0] - } - }; - - // Generate ordinal version of formatters: M -> Mo, D -> Do, etc. - var ordinalFormatters = ['M', 'D', 'DDD', 'd', 'Q', 'W']; - ordinalFormatters.forEach(function (formatterToken) { - formatters[formatterToken + 'o'] = function (date, formatters) { - return ordinal(formatters[formatterToken](date)) - }; - }); - - return { - formatters: formatters, - formattingTokensRegExp: build_formatting_tokens_reg_exp(formatters) - } -} - -function ordinal (number) { - var rem100 = number % 100; - if (rem100 > 20 || rem100 < 10) { - switch (rem100 % 10) { - case 1: - return number + 'st' - case 2: - return number + 'nd' - case 3: - return number + 'rd' - } - } - return number + 'th' -} - -var build_format_locale = buildFormatLocale; - -/** - * @category Locales - * @summary English locale. - */ -var en = { - distanceInWords: build_distance_in_words_locale(), - format: build_format_locale() -}; - -var MINUTES_IN_DAY$1 = 1440; -var MINUTES_IN_ALMOST_TWO_DAYS = 2520; -var MINUTES_IN_MONTH$1 = 43200; -var MINUTES_IN_TWO_MONTHS = 86400; - -/** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words. - * - * | Distance between dates | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance between dates | Result | - * |------------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWords( - * new Date(2014, 6, 2), - * new Date(2015, 0, 1) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00, including seconds? - * var result = distanceInWords( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWords( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> 'about 1 year ago' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWords( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ -function distanceInWords (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = Math.round(seconds / 60) - offset; - var months; - - // 0 up to 2 mins - if (minutes < 2) { - if (options.includeSeconds) { - if (seconds < 5) { - return localize('lessThanXSeconds', 5, localizeOptions) - } else if (seconds < 10) { - return localize('lessThanXSeconds', 10, localizeOptions) - } else if (seconds < 20) { - return localize('lessThanXSeconds', 20, localizeOptions) - } else if (seconds < 40) { - return localize('halfAMinute', null, localizeOptions) - } else if (seconds < 60) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', 1, localizeOptions) - } - } else { - if (minutes === 0) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', minutes, localizeOptions) - } - } - - // 2 mins up to 0.75 hrs - } else if (minutes < 45) { - return localize('xMinutes', minutes, localizeOptions) - - // 0.75 hrs up to 1.5 hrs - } else if (minutes < 90) { - return localize('aboutXHours', 1, localizeOptions) - - // 1.5 hrs up to 24 hrs - } else if (minutes < MINUTES_IN_DAY$1) { - var hours = Math.round(minutes / 60); - return localize('aboutXHours', hours, localizeOptions) - - // 1 day up to 1.75 days - } else if (minutes < MINUTES_IN_ALMOST_TWO_DAYS) { - return localize('xDays', 1, localizeOptions) - - // 1.75 days up to 30 days - } else if (minutes < MINUTES_IN_MONTH$1) { - var days = Math.round(minutes / MINUTES_IN_DAY$1); - return localize('xDays', days, localizeOptions) - - // 1 month up to 2 months - } else if (minutes < MINUTES_IN_TWO_MONTHS) { - months = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('aboutXMonths', months, localizeOptions) - } - - months = difference_in_months(dateRight, dateLeft); - - // 2 months up to 12 months - if (months < 12) { - var nearestMonth = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('xMonths', nearestMonth, localizeOptions) - - // 1 year up to max Date - } else { - var monthsSinceStartOfYear = months % 12; - var years = Math.floor(months / 12); - - // N years up to 1 years 3 months - if (monthsSinceStartOfYear < 3) { - return localize('aboutXYears', years, localizeOptions) - - // N years 3 months up to N years 9 months - } else if (monthsSinceStartOfYear < 9) { - return localize('overXYears', years, localizeOptions) - - // N years 9 months up to N year 12 months - } else { - return localize('almostXYears', years + 1, localizeOptions) - } - } -} - -var distance_in_words = distanceInWords; - -var MINUTES_IN_DAY = 1440; -var MINUTES_IN_MONTH = 43200; -var MINUTES_IN_YEAR = 525600; - -/** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words, using strict units. - * This is like `distanceInWords`, but does not use helpers like 'almost', 'over', - * 'less than' and the like. - * - * | Distance between dates | Result | - * |------------------------|---------------------| - * | 0 ... 59 secs | [0..59] seconds | - * | 1 ... 59 mins | [1..59] minutes | - * | 1 ... 23 hrs | [1..23] hours | - * | 1 ... 29 days | [1..29] days | - * | 1 ... 11 months | [1..11] months | - * | 1 ... N years | [1..N] years | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {'s'|'m'|'h'|'d'|'M'|'Y'} [options.unit] - if specified, will force a unit - * @param {'floor'|'ceil'|'round'} [options.partialMethod='floor'] - which way to round partial units - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWordsStrict( - * new Date(2014, 6, 2), - * new Date(2015, 0, 2) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * ) - * //=> '15 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> '1 year ago' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, in minutes? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {unit: 'm'} - * ) - * //=> '525600 minutes' - * - * @example - * // What is the distance from 1 January 2016 - * // to 28 January 2015, in months, rounded up? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 28), - * new Date(2015, 0, 1), - * {unit: 'M', partialMethod: 'ceil'} - * ) - * //=> '1 month' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsStrict( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> '1 jaro' - */ -function distanceInWordsStrict (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var unit; - var mathPartial = Math[options.partialMethod ? String(options.partialMethod) : 'floor']; - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = mathPartial(seconds / 60) - offset; - var hours, days, months, years; - - if (options.unit) { - unit = String(options.unit); - } else { - if (minutes < 1) { - unit = 's'; - } else if (minutes < 60) { - unit = 'm'; - } else if (minutes < MINUTES_IN_DAY) { - unit = 'h'; - } else if (minutes < MINUTES_IN_MONTH) { - unit = 'd'; - } else if (minutes < MINUTES_IN_YEAR) { - unit = 'M'; - } else { - unit = 'Y'; - } - } - - // 0 up to 60 seconds - if (unit === 's') { - return localize('xSeconds', seconds, localizeOptions) - - // 1 up to 60 mins - } else if (unit === 'm') { - return localize('xMinutes', minutes, localizeOptions) - - // 1 up to 24 hours - } else if (unit === 'h') { - hours = mathPartial(minutes / 60); - return localize('xHours', hours, localizeOptions) - - // 1 up to 30 days - } else if (unit === 'd') { - days = mathPartial(minutes / MINUTES_IN_DAY); - return localize('xDays', days, localizeOptions) - - // 1 up to 12 months - } else if (unit === 'M') { - months = mathPartial(minutes / MINUTES_IN_MONTH); - return localize('xMonths', months, localizeOptions) - - // 1 year up to max Date - } else if (unit === 'Y') { - years = mathPartial(minutes / MINUTES_IN_YEAR); - return localize('xYears', years, localizeOptions) - } - - throw new Error('Unknown unit: ' + unit) -} - -var distance_in_words_strict = distanceInWordsStrict; - -/** - * @category Common Helpers - * @summary Return the distance between the given date and now in words. - * - * @description - * Return the distance between the given date and now in words. - * - * | Distance to now | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance to now | Result | - * |---------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} date - the given date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result specifies if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // If today is 1 January 2015, what is the distance to 2 July 2014? - * var result = distanceInWordsToNow( - * new Date(2014, 6, 2) - * ) - * //=> '6 months' - * - * @example - * // If now is 1 January 2015 00:00:00, - * // what is the distance to 1 January 2015 00:00:15, including seconds? - * var result = distanceInWordsToNow( - * new Date(2015, 0, 1, 0, 0, 15), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 January 2016, with a suffix? - * var result = distanceInWordsToNow( - * new Date(2016, 0, 1), - * {addSuffix: true} - * ) - * //=> 'in about 1 year' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 August 2016 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsToNow( - * new Date(2016, 7, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ -function distanceInWordsToNow (dirtyDate, dirtyOptions) { - return distance_in_words(Date.now(), dirtyDate, dirtyOptions) -} - -var distance_in_words_to_now = distanceInWordsToNow; - -/** - * @category Day Helpers - * @summary Return the array of dates within the specified range. - * - * @description - * Return the array of dates within the specified range. - * - * @param {Date|String|Number} startDate - the first date - * @param {Date|String|Number} endDate - the last date - * @param {Number} [step=1] - the step between each day - * @returns {Date[]} the array with starts of days from the day of startDate to the day of endDate - * @throws {Error} startDate cannot be after endDate - * - * @example - * // Each day between 6 October 2014 and 10 October 2014: - * var result = eachDay( - * new Date(2014, 9, 6), - * new Date(2014, 9, 10) - * ) - * //=> [ - * // Mon Oct 06 2014 00:00:00, - * // Tue Oct 07 2014 00:00:00, - * // Wed Oct 08 2014 00:00:00, - * // Thu Oct 09 2014 00:00:00, - * // Fri Oct 10 2014 00:00:00 - * // ] - */ -function eachDay (dirtyStartDate, dirtyEndDate, dirtyStep) { - var startDate = parse_1(dirtyStartDate); - var endDate = parse_1(dirtyEndDate); - var step = dirtyStep !== undefined ? dirtyStep : 1; - - var endTime = endDate.getTime(); - - if (startDate.getTime() > endTime) { - throw new Error('The first date cannot be after the second date') - } - - var dates = []; - - var currentDate = startDate; - currentDate.setHours(0, 0, 0, 0); - - while (currentDate.getTime() <= endTime) { - dates.push(parse_1(currentDate)); - currentDate.setDate(currentDate.getDate() + step); - } - - return dates -} - -var each_day = eachDay; - -/** - * @category Day Helpers - * @summary Return the end of a day for the given date. - * - * @description - * Return the end of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a day - * - * @example - * // The end of a day for 2 September 2014 11:55:00: - * var result = endOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 23:59:59.999 - */ -function endOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_day = endOfDay; - -/** - * @category Hour Helpers - * @summary Return the end of an hour for the given date. - * - * @description - * Return the end of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an hour - * - * @example - * // The end of an hour for 2 September 2014 11:55:00: - * var result = endOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:59:59.999 - */ -function endOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(59, 59, 999); - return date -} - -var end_of_hour = endOfHour; - -/** - * @category Week Helpers - * @summary Return the end of a week for the given date. - * - * @description - * Return the end of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the end of a week - * - * @example - * // The end of a week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 23:59:59.999 - * - * @example - * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 23:59:59.999 - */ -function endOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setDate(date.getDate() + diff); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_week = endOfWeek; - -/** - * @category ISO Week Helpers - * @summary Return the end of an ISO week for the given date. - * - * @description - * Return the end of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week - * - * @example - * // The end of an ISO week for 2 September 2014 11:55:00: - * var result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 23:59:59.999 - */ -function endOfISOWeek (dirtyDate) { - return end_of_week(dirtyDate, {weekStartsOn: 1}) -} - -var end_of_iso_week = endOfISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Return the end of an ISO week-numbering year for the given date. - * - * @description - * Return the end of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The end of an ISO week-numbering year for 2 July 2005: - * var result = endOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 23:59:59.999 - */ -function endOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuaryOfNextYear); - date.setMilliseconds(date.getMilliseconds() - 1); - return date -} - -var end_of_iso_year = endOfISOYear; - -/** - * @category Minute Helpers - * @summary Return the end of a minute for the given date. - * - * @description - * Return the end of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a minute - * - * @example - * // The end of a minute for 1 December 2014 22:15:45.400: - * var result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:59.999 - */ -function endOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(59, 999); - return date -} - -var end_of_minute = endOfMinute; - -/** - * @category Month Helpers - * @summary Return the end of a month for the given date. - * - * @description - * Return the end of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a month - * - * @example - * // The end of a month for 2 September 2014 11:55:00: - * var result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ -function endOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_month = endOfMonth; - -/** - * @category Quarter Helpers - * @summary Return the end of a year quarter for the given date. - * - * @description - * Return the end of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a quarter - * - * @example - * // The end of a quarter for 2 September 2014 11:55:00: - * var result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ -function endOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_quarter = endOfQuarter; - -/** - * @category Second Helpers - * @summary Return the end of a second for the given date. - * - * @description - * Return the end of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a second - * - * @example - * // The end of a second for 1 December 2014 22:15:45.400: - * var result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.999 - */ -function endOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(999); - return date -} - -var end_of_second = endOfSecond; - -/** - * @category Day Helpers - * @summary Return the end of today. - * - * @description - * Return the end of today. - * - * @returns {Date} the end of today - * - * @example - * // If today is 6 October 2014: - * var result = endOfToday() - * //=> Mon Oct 6 2014 23:59:59.999 - */ -function endOfToday () { - return end_of_day(new Date()) -} - -var end_of_today = endOfToday; - -/** - * @category Day Helpers - * @summary Return the end of tomorrow. - * - * @description - * Return the end of tomorrow. - * - * @returns {Date} the end of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = endOfTomorrow() - * //=> Tue Oct 7 2014 23:59:59.999 - */ -function endOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_tomorrow = endOfTomorrow; - -/** - * @category Year Helpers - * @summary Return the end of a year for the given date. - * - * @description - * Return the end of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a year - * - * @example - * // The end of a year for 2 September 2014 11:55:00: - * var result = endOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 23:59:59.999 - */ -function endOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_year = endOfYear; - -/** - * @category Day Helpers - * @summary Return the end of yesterday. - * - * @description - * Return the end of yesterday. - * - * @returns {Date} the end of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = endOfYesterday() - * //=> Sun Oct 5 2014 23:59:59.999 - */ -function endOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(23, 59, 59, 999); - return date -} - -var end_of_yesterday = endOfYesterday; - -/** - * @category Year Helpers - * @summary Return the start of a year for the given date. - * - * @description - * Return the start of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a year - * - * @example - * // The start of a year for 2 September 2014 11:55:00: - * var result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Jan 01 2014 00:00:00 - */ -function startOfYear (dirtyDate) { - var cleanDate = parse_1(dirtyDate); - var date = new Date(0); - date.setFullYear(cleanDate.getFullYear(), 0, 1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_year = startOfYear; - -/** - * @category Day Helpers - * @summary Get the day of the year of the given date. - * - * @description - * Get the day of the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of year - * - * @example - * // Which day of the year is 2 July 2014? - * var result = getDayOfYear(new Date(2014, 6, 2)) - * //=> 183 - */ -function getDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = difference_in_calendar_days(date, start_of_year(date)); - var dayOfYear = diff + 1; - return dayOfYear -} - -var get_day_of_year = getDayOfYear; - -var MILLISECONDS_IN_WEEK$1 = 604800000; - -/** - * @category ISO Week Helpers - * @summary Get the ISO week of the given date. - * - * @description - * Get the ISO week of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week - * - * @example - * // Which week of the ISO-week numbering year is 2 January 2005? - * var result = getISOWeek(new Date(2005, 0, 2)) - * //=> 53 - */ -function getISOWeek (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = start_of_iso_week(date).getTime() - start_of_iso_year(date).getTime(); - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1 -} - -var get_iso_week = getISOWeek; - -/** - * @category Common Helpers - * @summary Is the given date valid? - * - * @description - * Returns false if argument is Invalid Date and true otherwise. - * Invalid Date is a Date, whose time value is NaN. - * - * Time value of Date: http://es5.github.io/#x15.9.1.1 - * - * @param {Date} date - the date to check - * @returns {Boolean} the date is valid - * @throws {TypeError} argument must be an instance of Date - * - * @example - * // For the valid date: - * var result = isValid(new Date(2014, 1, 31)) - * //=> true - * - * @example - * // For the invalid date: - * var result = isValid(new Date('')) - * //=> false - */ -function isValid (dirtyDate) { - if (is_date(dirtyDate)) { - return !isNaN(dirtyDate) - } else { - throw new TypeError(toString.call(dirtyDate) + ' is not an instance of Date') - } -} - -var is_valid = isValid; - -/** - * @category Common Helpers - * @summary Format the date. - * - * @description - * Return the formatted date string in the given format. - * - * Accepted tokens: - * | Unit | Token | Result examples | - * |-------------------------|-------|----------------------------------| - * | Month | M | 1, 2, ..., 12 | - * | | Mo | 1st, 2nd, ..., 12th | - * | | MM | 01, 02, ..., 12 | - * | | MMM | Jan, Feb, ..., Dec | - * | | MMMM | January, February, ..., December | - * | Quarter | Q | 1, 2, 3, 4 | - * | | Qo | 1st, 2nd, 3rd, 4th | - * | Day of month | D | 1, 2, ..., 31 | - * | | Do | 1st, 2nd, ..., 31st | - * | | DD | 01, 02, ..., 31 | - * | Day of year | DDD | 1, 2, ..., 366 | - * | | DDDo | 1st, 2nd, ..., 366th | - * | | DDDD | 001, 002, ..., 366 | - * | Day of week | d | 0, 1, ..., 6 | - * | | do | 0th, 1st, ..., 6th | - * | | dd | Su, Mo, ..., Sa | - * | | ddd | Sun, Mon, ..., Sat | - * | | dddd | Sunday, Monday, ..., Saturday | - * | Day of ISO week | E | 1, 2, ..., 7 | - * | ISO week | W | 1, 2, ..., 53 | - * | | Wo | 1st, 2nd, ..., 53rd | - * | | WW | 01, 02, ..., 53 | - * | Year | YY | 00, 01, ..., 99 | - * | | YYYY | 1900, 1901, ..., 2099 | - * | ISO week-numbering year | GG | 00, 01, ..., 99 | - * | | GGGG | 1900, 1901, ..., 2099 | - * | AM/PM | A | AM, PM | - * | | a | am, pm | - * | | aa | a.m., p.m. | - * | Hour | H | 0, 1, ... 23 | - * | | HH | 00, 01, ... 23 | - * | | h | 1, 2, ..., 12 | - * | | hh | 01, 02, ..., 12 | - * | Minute | m | 0, 1, ..., 59 | - * | | mm | 00, 01, ..., 59 | - * | Second | s | 0, 1, ..., 59 | - * | | ss | 00, 01, ..., 59 | - * | 1/10 of second | S | 0, 1, ..., 9 | - * | 1/100 of second | SS | 00, 01, ..., 99 | - * | Millisecond | SSS | 000, 001, ..., 999 | - * | Timezone | Z | -01:00, +00:00, ... +12:00 | - * | | ZZ | -0100, +0000, ..., +1200 | - * | Seconds timestamp | X | 512969520 | - * | Milliseconds timestamp | x | 512969520900 | - * - * The characters wrapped in square brackets are escaped. - * - * The result may vary by locale. - * - * @param {Date|String|Number} date - the original date - * @param {String} [format='YYYY-MM-DDTHH:mm:ss.SSSZ'] - the string of tokens - * @param {Object} [options] - the object with options - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the formatted date string - * - * @example - * // Represent 11 February 2014 in middle-endian format: - * var result = format( - * new Date(2014, 1, 11), - * 'MM/DD/YYYY' - * ) - * //=> '02/11/2014' - * - * @example - * // Represent 2 July 2014 in Esperanto: - * var eoLocale = require('date-fns/locale/eo') - * var result = format( - * new Date(2014, 6, 2), - * 'Do [de] MMMM YYYY', - * {locale: eoLocale} - * ) - * //=> '2-a de julio 2014' - */ -function format (dirtyDate, dirtyFormatStr, dirtyOptions) { - var formatStr = dirtyFormatStr ? String(dirtyFormatStr) : 'YYYY-MM-DDTHH:mm:ss.SSSZ'; - var options = dirtyOptions || {}; - - var locale = options.locale; - var localeFormatters = en.format.formatters; - var formattingTokensRegExp = en.format.formattingTokensRegExp; - if (locale && locale.format && locale.format.formatters) { - localeFormatters = locale.format.formatters; - - if (locale.format.formattingTokensRegExp) { - formattingTokensRegExp = locale.format.formattingTokensRegExp; - } - } - - var date = parse_1(dirtyDate); - - if (!is_valid(date)) { - return 'Invalid Date' - } - - var formatFn = buildFormatFn(formatStr, localeFormatters, formattingTokensRegExp); - - return formatFn(date) -} - -var formatters = { - // Month: 1, 2, ..., 12 - 'M': function (date) { - return date.getMonth() + 1 - }, - - // Month: 01, 02, ..., 12 - 'MM': function (date) { - return addLeadingZeros(date.getMonth() + 1, 2) - }, - - // Quarter: 1, 2, 3, 4 - 'Q': function (date) { - return Math.ceil((date.getMonth() + 1) / 3) - }, - - // Day of month: 1, 2, ..., 31 - 'D': function (date) { - return date.getDate() - }, - - // Day of month: 01, 02, ..., 31 - 'DD': function (date) { - return addLeadingZeros(date.getDate(), 2) - }, - - // Day of year: 1, 2, ..., 366 - 'DDD': function (date) { - return get_day_of_year(date) - }, - - // Day of year: 001, 002, ..., 366 - 'DDDD': function (date) { - return addLeadingZeros(get_day_of_year(date), 3) - }, - - // Day of week: 0, 1, ..., 6 - 'd': function (date) { - return date.getDay() - }, - - // Day of ISO week: 1, 2, ..., 7 - 'E': function (date) { - return date.getDay() || 7 - }, - - // ISO week: 1, 2, ..., 53 - 'W': function (date) { - return get_iso_week(date) - }, - - // ISO week: 01, 02, ..., 53 - 'WW': function (date) { - return addLeadingZeros(get_iso_week(date), 2) - }, - - // Year: 00, 01, ..., 99 - 'YY': function (date) { - return addLeadingZeros(date.getFullYear(), 4).substr(2) - }, - - // Year: 1900, 1901, ..., 2099 - 'YYYY': function (date) { - return addLeadingZeros(date.getFullYear(), 4) - }, - - // ISO week-numbering year: 00, 01, ..., 99 - 'GG': function (date) { - return String(get_iso_year(date)).substr(2) - }, - - // ISO week-numbering year: 1900, 1901, ..., 2099 - 'GGGG': function (date) { - return get_iso_year(date) - }, - - // Hour: 0, 1, ... 23 - 'H': function (date) { - return date.getHours() - }, - - // Hour: 00, 01, ..., 23 - 'HH': function (date) { - return addLeadingZeros(date.getHours(), 2) - }, - - // Hour: 1, 2, ..., 12 - 'h': function (date) { - var hours = date.getHours(); - if (hours === 0) { - return 12 - } else if (hours > 12) { - return hours % 12 - } else { - return hours - } - }, - - // Hour: 01, 02, ..., 12 - 'hh': function (date) { - return addLeadingZeros(formatters['h'](date), 2) - }, - - // Minute: 0, 1, ..., 59 - 'm': function (date) { - return date.getMinutes() - }, - - // Minute: 00, 01, ..., 59 - 'mm': function (date) { - return addLeadingZeros(date.getMinutes(), 2) - }, - - // Second: 0, 1, ..., 59 - 's': function (date) { - return date.getSeconds() - }, - - // Second: 00, 01, ..., 59 - 'ss': function (date) { - return addLeadingZeros(date.getSeconds(), 2) - }, - - // 1/10 of second: 0, 1, ..., 9 - 'S': function (date) { - return Math.floor(date.getMilliseconds() / 100) - }, - - // 1/100 of second: 00, 01, ..., 99 - 'SS': function (date) { - return addLeadingZeros(Math.floor(date.getMilliseconds() / 10), 2) - }, - - // Millisecond: 000, 001, ..., 999 - 'SSS': function (date) { - return addLeadingZeros(date.getMilliseconds(), 3) - }, - - // Timezone: -01:00, +00:00, ... +12:00 - 'Z': function (date) { - return formatTimezone(date.getTimezoneOffset(), ':') - }, - - // Timezone: -0100, +0000, ... +1200 - 'ZZ': function (date) { - return formatTimezone(date.getTimezoneOffset()) - }, - - // Seconds timestamp: 512969520 - 'X': function (date) { - return Math.floor(date.getTime() / 1000) - }, - - // Milliseconds timestamp: 512969520900 - 'x': function (date) { - return date.getTime() - } -}; - -function buildFormatFn (formatStr, localeFormatters, formattingTokensRegExp) { - var array = formatStr.match(formattingTokensRegExp); - var length = array.length; - - var i; - var formatter; - for (i = 0; i < length; i++) { - formatter = localeFormatters[array[i]] || formatters[array[i]]; - if (formatter) { - array[i] = formatter; - } else { - array[i] = removeFormattingTokens(array[i]); - } - } - - return function (date) { - var output = ''; - for (var i = 0; i < length; i++) { - if (array[i] instanceof Function) { - output += array[i](date, formatters); - } else { - output += array[i]; - } - } - return output - } -} - -function removeFormattingTokens (input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|]$/g, '') - } - return input.replace(/\\/g, '') -} - -function formatTimezone (offset, delimeter) { - delimeter = delimeter || ''; - var sign = offset > 0 ? '-' : '+'; - var absOffset = Math.abs(offset); - var hours = Math.floor(absOffset / 60); - var minutes = absOffset % 60; - return sign + addLeadingZeros(hours, 2) + delimeter + addLeadingZeros(minutes, 2) -} - -function addLeadingZeros (number, targetLength) { - var output = Math.abs(number).toString(); - while (output.length < targetLength) { - output = '0' + output; - } - return output -} - -var format_1 = format; - -/** - * @category Day Helpers - * @summary Get the day of the month of the given date. - * - * @description - * Get the day of the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of month - * - * @example - * // Which day of the month is 29 February 2012? - * var result = getDate(new Date(2012, 1, 29)) - * //=> 29 - */ -function getDate (dirtyDate) { - var date = parse_1(dirtyDate); - var dayOfMonth = date.getDate(); - return dayOfMonth -} - -var get_date = getDate; - -/** - * @category Weekday Helpers - * @summary Get the day of the week of the given date. - * - * @description - * Get the day of the week of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of week - * - * @example - * // Which day of the week is 29 February 2012? - * var result = getDay(new Date(2012, 1, 29)) - * //=> 3 - */ -function getDay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day -} - -var get_day = getDay; - -/** - * @category Year Helpers - * @summary Is the given date in the leap year? - * - * @description - * Is the given date in the leap year? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the leap year - * - * @example - * // Is 1 September 2012 in the leap year? - * var result = isLeapYear(new Date(2012, 8, 1)) - * //=> true - */ -function isLeapYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0 -} - -var is_leap_year = isLeapYear; - -/** - * @category Year Helpers - * @summary Get the number of days in a year of the given date. - * - * @description - * Get the number of days in a year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a year - * - * @example - * // How many days are in 2012? - * var result = getDaysInYear(new Date(2012, 0, 1)) - * //=> 366 - */ -function getDaysInYear (dirtyDate) { - return is_leap_year(dirtyDate) ? 366 : 365 -} - -var get_days_in_year = getDaysInYear; - -/** - * @category Hour Helpers - * @summary Get the hours of the given date. - * - * @description - * Get the hours of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the hours - * - * @example - * // Get the hours of 29 February 2012 11:45:00: - * var result = getHours(new Date(2012, 1, 29, 11, 45)) - * //=> 11 - */ -function getHours (dirtyDate) { - var date = parse_1(dirtyDate); - var hours = date.getHours(); - return hours -} - -var get_hours = getHours; - -/** - * @category Weekday Helpers - * @summary Get the day of the ISO week of the given date. - * - * @description - * Get the day of the ISO week of the given date, - * which is 7 for Sunday, 1 for Monday etc. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of ISO week - * - * @example - * // Which day of the ISO week is 26 February 2012? - * var result = getISODay(new Date(2012, 1, 26)) - * //=> 7 - */ -function getISODay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - - if (day === 0) { - day = 7; - } - - return day -} - -var get_iso_day = getISODay; - -var MILLISECONDS_IN_WEEK = 604800000; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of weeks in an ISO week-numbering year of the given date. - * - * @description - * Get the number of weeks in an ISO week-numbering year of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of ISO weeks in a year - * - * @example - * // How many weeks are in ISO week-numbering year 2015? - * var result = getISOWeeksInYear(new Date(2015, 1, 11)) - * //=> 53 - */ -function getISOWeeksInYear (dirtyDate) { - var thisYear = start_of_iso_year(dirtyDate); - var nextYear = start_of_iso_year(add_weeks(thisYear, 60)); - var diff = nextYear.valueOf() - thisYear.valueOf(); - // Round the number of weeks to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK) -} - -var get_iso_weeks_in_year = getISOWeeksInYear; - -/** - * @category Millisecond Helpers - * @summary Get the milliseconds of the given date. - * - * @description - * Get the milliseconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the milliseconds - * - * @example - * // Get the milliseconds of 29 February 2012 11:45:05.123: - * var result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 123 - */ -function getMilliseconds (dirtyDate) { - var date = parse_1(dirtyDate); - var milliseconds = date.getMilliseconds(); - return milliseconds -} - -var get_milliseconds = getMilliseconds; - -/** - * @category Minute Helpers - * @summary Get the minutes of the given date. - * - * @description - * Get the minutes of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the minutes - * - * @example - * // Get the minutes of 29 February 2012 11:45:05: - * var result = getMinutes(new Date(2012, 1, 29, 11, 45, 5)) - * //=> 45 - */ -function getMinutes (dirtyDate) { - var date = parse_1(dirtyDate); - var minutes = date.getMinutes(); - return minutes -} - -var get_minutes = getMinutes; - -/** - * @category Month Helpers - * @summary Get the month of the given date. - * - * @description - * Get the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the month - * - * @example - * // Which month is 29 February 2012? - * var result = getMonth(new Date(2012, 1, 29)) - * //=> 1 - */ -function getMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - return month -} - -var get_month = getMonth; - -var MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000; - -/** - * @category Range Helpers - * @summary Get the number of days that overlap in two date ranges - * - * @description - * Get the number of days that overlap in two date ranges - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Number} the number of days that overlap in two date ranges - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges adds 1 for each started overlapping day: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> 3 - * - * @example - * // For non-overlapping date ranges returns 0: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> 0 - */ -function getOverlappingDaysInRanges (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - var isOverlapping = initialStartTime < comparedEndTime && comparedStartTime < initialEndTime; - - if (!isOverlapping) { - return 0 - } - - var overlapStartDate = comparedStartTime < initialStartTime - ? initialStartTime - : comparedStartTime; - - var overlapEndDate = comparedEndTime > initialEndTime - ? initialEndTime - : comparedEndTime; - - var differenceInMs = overlapEndDate - overlapStartDate; - - return Math.ceil(differenceInMs / MILLISECONDS_IN_DAY) -} - -var get_overlapping_days_in_ranges = getOverlappingDaysInRanges; - -/** - * @category Second Helpers - * @summary Get the seconds of the given date. - * - * @description - * Get the seconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the seconds - * - * @example - * // Get the seconds of 29 February 2012 11:45:05.123: - * var result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 5 - */ -function getSeconds (dirtyDate) { - var date = parse_1(dirtyDate); - var seconds = date.getSeconds(); - return seconds -} - -var get_seconds = getSeconds; - -/** - * @category Timestamp Helpers - * @summary Get the milliseconds timestamp of the given date. - * - * @description - * Get the milliseconds timestamp of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the timestamp - * - * @example - * // Get the timestamp of 29 February 2012 11:45:05.123: - * var result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 1330515905123 - */ -function getTime (dirtyDate) { - var date = parse_1(dirtyDate); - var timestamp = date.getTime(); - return timestamp -} - -var get_time = getTime; - -/** - * @category Year Helpers - * @summary Get the year of the given date. - * - * @description - * Get the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the year - * - * @example - * // Which year is 2 July 2014? - * var result = getYear(new Date(2014, 6, 2)) - * //=> 2014 - */ -function getYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year -} - -var get_year = getYear; - -/** - * @category Common Helpers - * @summary Is the first date after the second one? - * - * @description - * Is the first date after the second one? - * - * @param {Date|String|Number} date - the date that should be after the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is after the second date - * - * @example - * // Is 10 July 1989 after 11 February 1987? - * var result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> true - */ -function isAfter (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() > dateToCompare.getTime() -} - -var is_after = isAfter; - -/** - * @category Common Helpers - * @summary Is the first date before the second one? - * - * @description - * Is the first date before the second one? - * - * @param {Date|String|Number} date - the date that should be before the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is before the second date - * - * @example - * // Is 10 July 1989 before 11 February 1987? - * var result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> false - */ -function isBefore (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() < dateToCompare.getTime() -} - -var is_before = isBefore; - -/** - * @category Common Helpers - * @summary Are the given dates equal? - * - * @description - * Are the given dates equal? - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Boolean} the dates are equal - * - * @example - * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal? - * var result = isEqual( - * new Date(2014, 6, 2, 6, 30, 45, 0) - * new Date(2014, 6, 2, 6, 30, 45, 500) - * ) - * //=> false - */ -function isEqual (dirtyLeftDate, dirtyRightDate) { - var dateLeft = parse_1(dirtyLeftDate); - var dateRight = parse_1(dirtyRightDate); - return dateLeft.getTime() === dateRight.getTime() -} - -var is_equal = isEqual; - -/** - * @category Month Helpers - * @summary Is the given date the first day of a month? - * - * @description - * Is the given date the first day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the first day of a month - * - * @example - * // Is 1 September 2014 the first day of a month? - * var result = isFirstDayOfMonth(new Date(2014, 8, 1)) - * //=> true - */ -function isFirstDayOfMonth (dirtyDate) { - return parse_1(dirtyDate).getDate() === 1 -} - -var is_first_day_of_month = isFirstDayOfMonth; - -/** - * @category Weekday Helpers - * @summary Is the given date Friday? - * - * @description - * Is the given date Friday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Friday - * - * @example - * // Is 26 September 2014 Friday? - * var result = isFriday(new Date(2014, 8, 26)) - * //=> true - */ -function isFriday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 5 -} - -var is_friday = isFriday; - -/** - * @category Common Helpers - * @summary Is the given date in the future? - * - * @description - * Is the given date in the future? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the future - * - * @example - * // If today is 6 October 2014, is 31 December 2014 in the future? - * var result = isFuture(new Date(2014, 11, 31)) - * //=> true - */ -function isFuture (dirtyDate) { - return parse_1(dirtyDate).getTime() > new Date().getTime() -} - -var is_future = isFuture; - -/** - * @category Month Helpers - * @summary Is the given date the last day of a month? - * - * @description - * Is the given date the last day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the last day of a month - * - * @example - * // Is 28 February 2014 the last day of a month? - * var result = isLastDayOfMonth(new Date(2014, 1, 28)) - * //=> true - */ -function isLastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - return end_of_day(date).getTime() === end_of_month(date).getTime() -} - -var is_last_day_of_month = isLastDayOfMonth; - -/** - * @category Weekday Helpers - * @summary Is the given date Monday? - * - * @description - * Is the given date Monday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Monday - * - * @example - * // Is 22 September 2014 Monday? - * var result = isMonday(new Date(2014, 8, 22)) - * //=> true - */ -function isMonday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 1 -} - -var is_monday = isMonday; - -/** - * @category Common Helpers - * @summary Is the given date in the past? - * - * @description - * Is the given date in the past? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the past - * - * @example - * // If today is 6 October 2014, is 2 July 2014 in the past? - * var result = isPast(new Date(2014, 6, 2)) - * //=> true - */ -function isPast (dirtyDate) { - return parse_1(dirtyDate).getTime() < new Date().getTime() -} - -var is_past = isPast; - -/** - * @category Day Helpers - * @summary Are the given dates in the same day? - * - * @description - * Are the given dates in the same day? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same day - * - * @example - * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? - * var result = isSameDay( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 18, 0) - * ) - * //=> true - */ -function isSameDay (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfDay = start_of_day(dirtyDateLeft); - var dateRightStartOfDay = start_of_day(dirtyDateRight); - - return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime() -} - -var is_same_day = isSameDay; - -/** - * @category Hour Helpers - * @summary Return the start of an hour for the given date. - * - * @description - * Return the start of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an hour - * - * @example - * // The start of an hour for 2 September 2014 11:55:00: - * var result = startOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:00:00 - */ -function startOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(0, 0, 0); - return date -} - -var start_of_hour = startOfHour; - -/** - * @category Hour Helpers - * @summary Are the given dates in the same hour? - * - * @description - * Are the given dates in the same hour? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same hour - * - * @example - * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour? - * var result = isSameHour( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 6, 30) - * ) - * //=> true - */ -function isSameHour (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfHour = start_of_hour(dirtyDateLeft); - var dateRightStartOfHour = start_of_hour(dirtyDateRight); - - return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime() -} - -var is_same_hour = isSameHour; - -/** - * @category Week Helpers - * @summary Are the given dates in the same week? - * - * @description - * Are the given dates in the same week? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the dates are in the same week - * - * @example - * // Are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4) - * ) - * //=> true - * - * @example - * // If week starts with Monday, - * // are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4), - * {weekStartsOn: 1} - * ) - * //=> false - */ -function isSameWeek (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var dateLeftStartOfWeek = start_of_week(dirtyDateLeft, dirtyOptions); - var dateRightStartOfWeek = start_of_week(dirtyDateRight, dirtyOptions); - - return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime() -} - -var is_same_week = isSameWeek; - -/** - * @category ISO Week Helpers - * @summary Are the given dates in the same ISO week? - * - * @description - * Are the given dates in the same ISO week? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week - * - * @example - * // Are 1 September 2014 and 7 September 2014 in the same ISO week? - * var result = isSameISOWeek( - * new Date(2014, 8, 1), - * new Date(2014, 8, 7) - * ) - * //=> true - */ -function isSameISOWeek (dirtyDateLeft, dirtyDateRight) { - return is_same_week(dirtyDateLeft, dirtyDateRight, {weekStartsOn: 1}) -} - -var is_same_iso_week = isSameISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Are the given dates in the same ISO week-numbering year? - * - * @description - * Are the given dates in the same ISO week-numbering year? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week-numbering year - * - * @example - * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? - * var result = isSameISOYear( - * new Date(2003, 11, 29), - * new Date(2005, 0, 2) - * ) - * //=> true - */ -function isSameISOYear (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfYear = start_of_iso_year(dirtyDateLeft); - var dateRightStartOfYear = start_of_iso_year(dirtyDateRight); - - return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime() -} - -var is_same_iso_year = isSameISOYear; - -/** - * @category Minute Helpers - * @summary Return the start of a minute for the given date. - * - * @description - * Return the start of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a minute - * - * @example - * // The start of a minute for 1 December 2014 22:15:45.400: - * var result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:00 - */ -function startOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(0, 0); - return date -} - -var start_of_minute = startOfMinute; - -/** - * @category Minute Helpers - * @summary Are the given dates in the same minute? - * - * @description - * Are the given dates in the same minute? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same minute - * - * @example - * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 - * // in the same minute? - * var result = isSameMinute( - * new Date(2014, 8, 4, 6, 30), - * new Date(2014, 8, 4, 6, 30, 15) - * ) - * //=> true - */ -function isSameMinute (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfMinute = start_of_minute(dirtyDateLeft); - var dateRightStartOfMinute = start_of_minute(dirtyDateRight); - - return dateLeftStartOfMinute.getTime() === dateRightStartOfMinute.getTime() -} - -var is_same_minute = isSameMinute; - -/** - * @category Month Helpers - * @summary Are the given dates in the same month? - * - * @description - * Are the given dates in the same month? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same month - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same month? - * var result = isSameMonth( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ -function isSameMonth (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() && - dateLeft.getMonth() === dateRight.getMonth() -} - -var is_same_month = isSameMonth; - -/** - * @category Quarter Helpers - * @summary Return the start of a year quarter for the given date. - * - * @description - * Return the start of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a quarter - * - * @example - * // The start of a quarter for 2 September 2014 11:55:00: - * var result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Jul 01 2014 00:00:00 - */ -function startOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3; - date.setMonth(month, 1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_quarter = startOfQuarter; - -/** - * @category Quarter Helpers - * @summary Are the given dates in the same year quarter? - * - * @description - * Are the given dates in the same year quarter? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same quarter - * - * @example - * // Are 1 January 2014 and 8 March 2014 in the same quarter? - * var result = isSameQuarter( - * new Date(2014, 0, 1), - * new Date(2014, 2, 8) - * ) - * //=> true - */ -function isSameQuarter (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfQuarter = start_of_quarter(dirtyDateLeft); - var dateRightStartOfQuarter = start_of_quarter(dirtyDateRight); - - return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime() -} - -var is_same_quarter = isSameQuarter; - -/** - * @category Second Helpers - * @summary Return the start of a second for the given date. - * - * @description - * Return the start of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a second - * - * @example - * // The start of a second for 1 December 2014 22:15:45.400: - * var result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.000 - */ -function startOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(0); - return date -} - -var start_of_second = startOfSecond; - -/** - * @category Second Helpers - * @summary Are the given dates in the same second? - * - * @description - * Are the given dates in the same second? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same second - * - * @example - * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 - * // in the same second? - * var result = isSameSecond( - * new Date(2014, 8, 4, 6, 30, 15), - * new Date(2014, 8, 4, 6, 30, 15, 500) - * ) - * //=> true - */ -function isSameSecond (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfSecond = start_of_second(dirtyDateLeft); - var dateRightStartOfSecond = start_of_second(dirtyDateRight); - - return dateLeftStartOfSecond.getTime() === dateRightStartOfSecond.getTime() -} - -var is_same_second = isSameSecond; - -/** - * @category Year Helpers - * @summary Are the given dates in the same year? - * - * @description - * Are the given dates in the same year? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same year - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same year? - * var result = isSameYear( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ -function isSameYear (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() -} - -var is_same_year = isSameYear; - -/** - * @category Weekday Helpers - * @summary Is the given date Saturday? - * - * @description - * Is the given date Saturday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Saturday - * - * @example - * // Is 27 September 2014 Saturday? - * var result = isSaturday(new Date(2014, 8, 27)) - * //=> true - */ -function isSaturday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 6 -} - -var is_saturday = isSaturday; - -/** - * @category Weekday Helpers - * @summary Is the given date Sunday? - * - * @description - * Is the given date Sunday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Sunday - * - * @example - * // Is 21 September 2014 Sunday? - * var result = isSunday(new Date(2014, 8, 21)) - * //=> true - */ -function isSunday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 0 -} - -var is_sunday = isSunday; - -/** - * @category Hour Helpers - * @summary Is the given date in the same hour as the current date? - * - * @description - * Is the given date in the same hour as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this hour - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:00:00 in this hour? - * var result = isThisHour(new Date(2014, 8, 25, 18)) - * //=> true - */ -function isThisHour (dirtyDate) { - return is_same_hour(new Date(), dirtyDate) -} - -var is_this_hour = isThisHour; - -/** - * @category ISO Week Helpers - * @summary Is the given date in the same ISO week as the current date? - * - * @description - * Is the given date in the same ISO week as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week - * - * @example - * // If today is 25 September 2014, is 22 September 2014 in this ISO week? - * var result = isThisISOWeek(new Date(2014, 8, 22)) - * //=> true - */ -function isThisISOWeek (dirtyDate) { - return is_same_iso_week(new Date(), dirtyDate) -} - -var is_this_iso_week = isThisISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Is the given date in the same ISO week-numbering year as the current date? - * - * @description - * Is the given date in the same ISO week-numbering year as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week-numbering year - * - * @example - * // If today is 25 September 2014, - * // is 30 December 2013 in this ISO week-numbering year? - * var result = isThisISOYear(new Date(2013, 11, 30)) - * //=> true - */ -function isThisISOYear (dirtyDate) { - return is_same_iso_year(new Date(), dirtyDate) -} - -var is_this_iso_year = isThisISOYear; - -/** - * @category Minute Helpers - * @summary Is the given date in the same minute as the current date? - * - * @description - * Is the given date in the same minute as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this minute - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:00 in this minute? - * var result = isThisMinute(new Date(2014, 8, 25, 18, 30)) - * //=> true - */ -function isThisMinute (dirtyDate) { - return is_same_minute(new Date(), dirtyDate) -} - -var is_this_minute = isThisMinute; - -/** - * @category Month Helpers - * @summary Is the given date in the same month as the current date? - * - * @description - * Is the given date in the same month as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this month - * - * @example - * // If today is 25 September 2014, is 15 September 2014 in this month? - * var result = isThisMonth(new Date(2014, 8, 15)) - * //=> true - */ -function isThisMonth (dirtyDate) { - return is_same_month(new Date(), dirtyDate) -} - -var is_this_month = isThisMonth; - -/** - * @category Quarter Helpers - * @summary Is the given date in the same quarter as the current date? - * - * @description - * Is the given date in the same quarter as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this quarter - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this quarter? - * var result = isThisQuarter(new Date(2014, 6, 2)) - * //=> true - */ -function isThisQuarter (dirtyDate) { - return is_same_quarter(new Date(), dirtyDate) -} - -var is_this_quarter = isThisQuarter; - -/** - * @category Second Helpers - * @summary Is the given date in the same second as the current date? - * - * @description - * Is the given date in the same second as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this second - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:15.000 in this second? - * var result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15)) - * //=> true - */ -function isThisSecond (dirtyDate) { - return is_same_second(new Date(), dirtyDate) -} - -var is_this_second = isThisSecond; - -/** - * @category Week Helpers - * @summary Is the given date in the same week as the current date? - * - * @description - * Is the given date in the same week as the current date? - * - * @param {Date|String|Number} date - the date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the date is in this week - * - * @example - * // If today is 25 September 2014, is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21)) - * //=> true - * - * @example - * // If today is 25 September 2014 and week starts with Monday - * // is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21), {weekStartsOn: 1}) - * //=> false - */ -function isThisWeek (dirtyDate, dirtyOptions) { - return is_same_week(new Date(), dirtyDate, dirtyOptions) -} - -var is_this_week = isThisWeek; - -/** - * @category Year Helpers - * @summary Is the given date in the same year as the current date? - * - * @description - * Is the given date in the same year as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this year - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this year? - * var result = isThisYear(new Date(2014, 6, 2)) - * //=> true - */ -function isThisYear (dirtyDate) { - return is_same_year(new Date(), dirtyDate) -} - -var is_this_year = isThisYear; - -/** - * @category Weekday Helpers - * @summary Is the given date Thursday? - * - * @description - * Is the given date Thursday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Thursday - * - * @example - * // Is 25 September 2014 Thursday? - * var result = isThursday(new Date(2014, 8, 25)) - * //=> true - */ -function isThursday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 4 -} - -var is_thursday = isThursday; - -/** - * @category Day Helpers - * @summary Is the given date today? - * - * @description - * Is the given date today? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is today - * - * @example - * // If today is 6 October 2014, is 6 October 14:00:00 today? - * var result = isToday(new Date(2014, 9, 6, 14, 0)) - * //=> true - */ -function isToday (dirtyDate) { - return start_of_day(dirtyDate).getTime() === start_of_day(new Date()).getTime() -} - -var is_today = isToday; - -/** - * @category Day Helpers - * @summary Is the given date tomorrow? - * - * @description - * Is the given date tomorrow? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is tomorrow - * - * @example - * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow? - * var result = isTomorrow(new Date(2014, 9, 7, 14, 0)) - * //=> true - */ -function isTomorrow (dirtyDate) { - var tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 1); - return start_of_day(dirtyDate).getTime() === start_of_day(tomorrow).getTime() -} - -var is_tomorrow = isTomorrow; - -/** - * @category Weekday Helpers - * @summary Is the given date Tuesday? - * - * @description - * Is the given date Tuesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Tuesday - * - * @example - * // Is 23 September 2014 Tuesday? - * var result = isTuesday(new Date(2014, 8, 23)) - * //=> true - */ -function isTuesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 2 -} - -var is_tuesday = isTuesday; - -/** - * @category Weekday Helpers - * @summary Is the given date Wednesday? - * - * @description - * Is the given date Wednesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Wednesday - * - * @example - * // Is 24 September 2014 Wednesday? - * var result = isWednesday(new Date(2014, 8, 24)) - * //=> true - */ -function isWednesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 3 -} - -var is_wednesday = isWednesday; - -/** - * @category Weekday Helpers - * @summary Does the given date fall on a weekend? - * - * @description - * Does the given date fall on a weekend? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date falls on a weekend - * - * @example - * // Does 5 October 2014 fall on a weekend? - * var result = isWeekend(new Date(2014, 9, 5)) - * //=> true - */ -function isWeekend (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day === 0 || day === 6 -} - -var is_weekend = isWeekend; - -/** - * @category Range Helpers - * @summary Is the given date within the range? - * - * @description - * Is the given date within the range? - * - * @param {Date|String|Number} date - the date to check - * @param {Date|String|Number} startDate - the start of range - * @param {Date|String|Number} endDate - the end of range - * @returns {Boolean} the date is within the range - * @throws {Error} startDate cannot be after endDate - * - * @example - * // For the date within the range: - * isWithinRange( - * new Date(2014, 0, 3), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> true - * - * @example - * // For the date outside of the range: - * isWithinRange( - * new Date(2014, 0, 10), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> false - */ -function isWithinRange (dirtyDate, dirtyStartDate, dirtyEndDate) { - var time = parse_1(dirtyDate).getTime(); - var startTime = parse_1(dirtyStartDate).getTime(); - var endTime = parse_1(dirtyEndDate).getTime(); - - if (startTime > endTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return time >= startTime && time <= endTime -} - -var is_within_range = isWithinRange; - -/** - * @category Day Helpers - * @summary Is the given date yesterday? - * - * @description - * Is the given date yesterday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is yesterday - * - * @example - * // If today is 6 October 2014, is 5 October 14:00:00 yesterday? - * var result = isYesterday(new Date(2014, 9, 5, 14, 0)) - * //=> true - */ -function isYesterday (dirtyDate) { - var yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - return start_of_day(dirtyDate).getTime() === start_of_day(yesterday).getTime() -} - -var is_yesterday = isYesterday; - -/** - * @category Week Helpers - * @summary Return the last day of a week for the given date. - * - * @description - * Return the last day of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the last day of a week - * - * @example - * // The last day of a week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ -function lastDayOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setHours(0, 0, 0, 0); - date.setDate(date.getDate() + diff); - return date -} - -var last_day_of_week = lastDayOfWeek; - -/** - * @category ISO Week Helpers - * @summary Return the last day of an ISO week for the given date. - * - * @description - * Return the last day of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of an ISO week - * - * @example - * // The last day of an ISO week for 2 September 2014 11:55:00: - * var result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 00:00:00 - */ -function lastDayOfISOWeek (dirtyDate) { - return last_day_of_week(dirtyDate, {weekStartsOn: 1}) -} - -var last_day_of_iso_week = lastDayOfISOWeek; - -/** - * @category ISO Week-Numbering Year Helpers - * @summary Return the last day of an ISO week-numbering year for the given date. - * - * @description - * Return the last day of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The last day of an ISO week-numbering year for 2 July 2005: - * var result = lastDayOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 00:00:00 - */ -function lastDayOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year + 1, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - date.setDate(date.getDate() - 1); - return date -} - -var last_day_of_iso_year = lastDayOfISOYear; - -/** - * @category Month Helpers - * @summary Return the last day of a month for the given date. - * - * @description - * Return the last day of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a month - * - * @example - * // The last day of a month for 2 September 2014 11:55:00: - * var result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ -function lastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(0, 0, 0, 0); - return date -} - -var last_day_of_month = lastDayOfMonth; - -/** - * @category Quarter Helpers - * @summary Return the last day of a year quarter for the given date. - * - * @description - * Return the last day of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a quarter - * - * @example - * // The last day of a quarter for 2 September 2014 11:55:00: - * var result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ -function lastDayOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(0, 0, 0, 0); - return date -} - -var last_day_of_quarter = lastDayOfQuarter; - -/** - * @category Year Helpers - * @summary Return the last day of a year for the given date. - * - * @description - * Return the last day of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a year - * - * @example - * // The last day of a year for 2 September 2014 11:55:00: - * var result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 00:00:00 - */ -function lastDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(0, 0, 0, 0); - return date -} - -var last_day_of_year = lastDayOfYear; - -/** - * @category Common Helpers - * @summary Return the latest of the given dates. - * - * @description - * Return the latest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the latest of the dates - * - * @example - * // Which of these dates is the latest? - * var result = max( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Sun Jul 02 1995 00:00:00 - */ -function max () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var latestTimestamp = Math.max.apply(null, dates); - return new Date(latestTimestamp) -} - -var max_1 = max; - -/** - * @category Common Helpers - * @summary Return the earliest of the given dates. - * - * @description - * Return the earliest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the earliest of the dates - * - * @example - * // Which of these dates is the earliest? - * var result = min( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Wed Feb 11 1987 00:00:00 - */ -function min () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var earliestTimestamp = Math.min.apply(null, dates); - return new Date(earliestTimestamp) -} - -var min_1 = min; - -/** - * @category Day Helpers - * @summary Set the day of the month to the given date. - * - * @description - * Set the day of the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfMonth - the day of the month of the new date - * @returns {Date} the new date with the day of the month setted - * - * @example - * // Set the 30th day of the month to 1 September 2014: - * var result = setDate(new Date(2014, 8, 1), 30) - * //=> Tue Sep 30 2014 00:00:00 - */ -function setDate (dirtyDate, dirtyDayOfMonth) { - var date = parse_1(dirtyDate); - var dayOfMonth = Number(dirtyDayOfMonth); - date.setDate(dayOfMonth); - return date -} - -var set_date = setDate; - -/** - * @category Weekday Helpers - * @summary Set the day of the week to the given date. - * - * @description - * Set the day of the week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the week of the new date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the new date with the day of the week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If week starts with Monday, set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0, {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ -function setDay (dirtyDate, dirtyDay, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = date.getDay(); - - var remainder = day % 7; - var dayIndex = (remainder + 7) % 7; - - var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; - return add_days(date, diff) -} - -var set_day = setDay; - -/** - * @category Day Helpers - * @summary Set the day of the year to the given date. - * - * @description - * Set the day of the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfYear - the day of the year of the new date - * @returns {Date} the new date with the day of the year setted - * - * @example - * // Set the 2nd day of the year to 2 July 2014: - * var result = setDayOfYear(new Date(2014, 6, 2), 2) - * //=> Thu Jan 02 2014 00:00:00 - */ -function setDayOfYear (dirtyDate, dirtyDayOfYear) { - var date = parse_1(dirtyDate); - var dayOfYear = Number(dirtyDayOfYear); - date.setMonth(0); - date.setDate(dayOfYear); - return date -} - -var set_day_of_year = setDayOfYear; - -/** - * @category Hour Helpers - * @summary Set the hours to the given date. - * - * @description - * Set the hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} hours - the hours of the new date - * @returns {Date} the new date with the hours setted - * - * @example - * // Set 4 hours to 1 September 2014 11:30:00: - * var result = setHours(new Date(2014, 8, 1, 11, 30), 4) - * //=> Mon Sep 01 2014 04:30:00 - */ -function setHours (dirtyDate, dirtyHours) { - var date = parse_1(dirtyDate); - var hours = Number(dirtyHours); - date.setHours(hours); - return date -} - -var set_hours = setHours; - -/** - * @category Weekday Helpers - * @summary Set the day of the ISO week to the given date. - * - * @description - * Set the day of the ISO week to the given date. - * ISO week starts with Monday. - * 7 is the index of Sunday, 1 is the index of Monday etc. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the ISO week of the new date - * @returns {Date} the new date with the day of the ISO week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setISODay(new Date(2014, 8, 1), 7) - * //=> Sun Sep 07 2014 00:00:00 - */ -function setISODay (dirtyDate, dirtyDay) { - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = get_iso_day(date); - var diff = day - currentDay; - return add_days(date, diff) -} - -var set_iso_day = setISODay; - -/** - * @category ISO Week Helpers - * @summary Set the ISO week to the given date. - * - * @description - * Set the ISO week to the given date, saving the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoWeek - the ISO week of the new date - * @returns {Date} the new date with the ISO week setted - * - * @example - * // Set the 53rd ISO week to 7 August 2004: - * var result = setISOWeek(new Date(2004, 7, 7), 53) - * //=> Sat Jan 01 2005 00:00:00 - */ -function setISOWeek (dirtyDate, dirtyISOWeek) { - var date = parse_1(dirtyDate); - var isoWeek = Number(dirtyISOWeek); - var diff = get_iso_week(date) - isoWeek; - date.setDate(date.getDate() - diff * 7); - return date -} - -var set_iso_week = setISOWeek; - -/** - * @category Millisecond Helpers - * @summary Set the milliseconds to the given date. - * - * @description - * Set the milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} milliseconds - the milliseconds of the new date - * @returns {Date} the new date with the milliseconds setted - * - * @example - * // Set 300 milliseconds to 1 September 2014 11:30:40.500: - * var result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300) - * //=> Mon Sep 01 2014 11:30:40.300 - */ -function setMilliseconds (dirtyDate, dirtyMilliseconds) { - var date = parse_1(dirtyDate); - var milliseconds = Number(dirtyMilliseconds); - date.setMilliseconds(milliseconds); - return date -} - -var set_milliseconds = setMilliseconds; - -/** - * @category Minute Helpers - * @summary Set the minutes to the given date. - * - * @description - * Set the minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} minutes - the minutes of the new date - * @returns {Date} the new date with the minutes setted - * - * @example - * // Set 45 minutes to 1 September 2014 11:30:40: - * var result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:45:40 - */ -function setMinutes (dirtyDate, dirtyMinutes) { - var date = parse_1(dirtyDate); - var minutes = Number(dirtyMinutes); - date.setMinutes(minutes); - return date -} - -var set_minutes = setMinutes; - -/** - * @category Month Helpers - * @summary Set the month to the given date. - * - * @description - * Set the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} month - the month of the new date - * @returns {Date} the new date with the month setted - * - * @example - * // Set February to 1 September 2014: - * var result = setMonth(new Date(2014, 8, 1), 1) - * //=> Sat Feb 01 2014 00:00:00 - */ -function setMonth (dirtyDate, dirtyMonth) { - var date = parse_1(dirtyDate); - var month = Number(dirtyMonth); - var year = date.getFullYear(); - var day = date.getDate(); - - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(year, month, 15); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(month, Math.min(day, daysInMonth)); - return date -} - -var set_month = setMonth; - -/** - * @category Quarter Helpers - * @summary Set the year quarter to the given date. - * - * @description - * Set the year quarter to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} quarter - the quarter of the new date - * @returns {Date} the new date with the quarter setted - * - * @example - * // Set the 2nd quarter to 2 July 2014: - * var result = setQuarter(new Date(2014, 6, 2), 2) - * //=> Wed Apr 02 2014 00:00:00 - */ -function setQuarter (dirtyDate, dirtyQuarter) { - var date = parse_1(dirtyDate); - var quarter = Number(dirtyQuarter); - var oldQuarter = Math.floor(date.getMonth() / 3) + 1; - var diff = quarter - oldQuarter; - return set_month(date, date.getMonth() + diff * 3) -} - -var set_quarter = setQuarter; - -/** - * @category Second Helpers - * @summary Set the seconds to the given date. - * - * @description - * Set the seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} seconds - the seconds of the new date - * @returns {Date} the new date with the seconds setted - * - * @example - * // Set 45 seconds to 1 September 2014 11:30:40: - * var result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:30:45 - */ -function setSeconds (dirtyDate, dirtySeconds) { - var date = parse_1(dirtyDate); - var seconds = Number(dirtySeconds); - date.setSeconds(seconds); - return date -} - -var set_seconds = setSeconds; - -/** - * @category Year Helpers - * @summary Set the year to the given date. - * - * @description - * Set the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} year - the year of the new date - * @returns {Date} the new date with the year setted - * - * @example - * // Set year 2013 to 1 September 2014: - * var result = setYear(new Date(2014, 8, 1), 2013) - * //=> Sun Sep 01 2013 00:00:00 - */ -function setYear (dirtyDate, dirtyYear) { - var date = parse_1(dirtyDate); - var year = Number(dirtyYear); - date.setFullYear(year); - return date -} - -var set_year = setYear; - -/** - * @category Month Helpers - * @summary Return the start of a month for the given date. - * - * @description - * Return the start of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a month - * - * @example - * // The start of a month for 2 September 2014 11:55:00: - * var result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ -function startOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - date.setDate(1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_month = startOfMonth; - -/** - * @category Day Helpers - * @summary Return the start of today. - * - * @description - * Return the start of today. - * - * @returns {Date} the start of today - * - * @example - * // If today is 6 October 2014: - * var result = startOfToday() - * //=> Mon Oct 6 2014 00:00:00 - */ -function startOfToday () { - return start_of_day(new Date()) -} - -var start_of_today = startOfToday; - -/** - * @category Day Helpers - * @summary Return the start of tomorrow. - * - * @description - * Return the start of tomorrow. - * - * @returns {Date} the start of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = startOfTomorrow() - * //=> Tue Oct 7 2014 00:00:00 - */ -function startOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_tomorrow = startOfTomorrow; - -/** - * @category Day Helpers - * @summary Return the start of yesterday. - * - * @description - * Return the start of yesterday. - * - * @returns {Date} the start of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = startOfYesterday() - * //=> Sun Oct 5 2014 00:00:00 - */ -function startOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(0, 0, 0, 0); - return date -} - -var start_of_yesterday = startOfYesterday; - -/** - * @category Day Helpers - * @summary Subtract the specified number of days from the given date. - * - * @description - * Subtract the specified number of days from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be subtracted - * @returns {Date} the new date with the days subtracted - * - * @example - * // Subtract 10 days from 1 September 2014: - * var result = subDays(new Date(2014, 8, 1), 10) - * //=> Fri Aug 22 2014 00:00:00 - */ -function subDays (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_days(dirtyDate, -amount) -} - -var sub_days = subDays; - -/** - * @category Hour Helpers - * @summary Subtract the specified number of hours from the given date. - * - * @description - * Subtract the specified number of hours from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be subtracted - * @returns {Date} the new date with the hours subtracted - * - * @example - * // Subtract 2 hours from 11 July 2014 01:00:00: - * var result = subHours(new Date(2014, 6, 11, 1, 0), 2) - * //=> Thu Jul 10 2014 23:00:00 - */ -function subHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_hours(dirtyDate, -amount) -} - -var sub_hours = subHours; - -/** - * @category Millisecond Helpers - * @summary Subtract the specified number of milliseconds from the given date. - * - * @description - * Subtract the specified number of milliseconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be subtracted - * @returns {Date} the new date with the milliseconds subtracted - * - * @example - * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: - * var result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:29.250 - */ -function subMilliseconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, -amount) -} - -var sub_milliseconds = subMilliseconds; - -/** - * @category Minute Helpers - * @summary Subtract the specified number of minutes from the given date. - * - * @description - * Subtract the specified number of minutes from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be subtracted - * @returns {Date} the new date with the mintues subtracted - * - * @example - * // Subtract 30 minutes from 10 July 2014 12:00:00: - * var result = subMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 11:30:00 - */ -function subMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_minutes(dirtyDate, -amount) -} - -var sub_minutes = subMinutes; - -/** - * @category Month Helpers - * @summary Subtract the specified number of months from the given date. - * - * @description - * Subtract the specified number of months from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be subtracted - * @returns {Date} the new date with the months subtracted - * - * @example - * // Subtract 5 months from 1 February 2015: - * var result = subMonths(new Date(2015, 1, 1), 5) - * //=> Mon Sep 01 2014 00:00:00 - */ -function subMonths (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, -amount) -} - -var sub_months = subMonths; - -/** - * @category Quarter Helpers - * @summary Subtract the specified number of year quarters from the given date. - * - * @description - * Subtract the specified number of year quarters from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be subtracted - * @returns {Date} the new date with the quarters subtracted - * - * @example - * // Subtract 3 quarters from 1 September 2014: - * var result = subQuarters(new Date(2014, 8, 1), 3) - * //=> Sun Dec 01 2013 00:00:00 - */ -function subQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_quarters(dirtyDate, -amount) -} - -var sub_quarters = subQuarters; - -/** - * @category Second Helpers - * @summary Subtract the specified number of seconds from the given date. - * - * @description - * Subtract the specified number of seconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be subtracted - * @returns {Date} the new date with the seconds subtracted - * - * @example - * // Subtract 30 seconds from 10 July 2014 12:45:00: - * var result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:44:30 - */ -function subSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_seconds(dirtyDate, -amount) -} - -var sub_seconds = subSeconds; - -/** - * @category Week Helpers - * @summary Subtract the specified number of weeks from the given date. - * - * @description - * Subtract the specified number of weeks from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be subtracted - * @returns {Date} the new date with the weeks subtracted - * - * @example - * // Subtract 4 weeks from 1 September 2014: - * var result = subWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Aug 04 2014 00:00:00 - */ -function subWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_weeks(dirtyDate, -amount) -} - -var sub_weeks = subWeeks; - -/** - * @category Year Helpers - * @summary Subtract the specified number of years from the given date. - * - * @description - * Subtract the specified number of years from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be subtracted - * @returns {Date} the new date with the years subtracted - * - * @example - * // Subtract 5 years from 1 September 2014: - * var result = subYears(new Date(2014, 8, 1), 5) - * //=> Tue Sep 01 2009 00:00:00 - */ -function subYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_years(dirtyDate, -amount) -} - -var sub_years = subYears; - -var dateFns = { - addDays: add_days, - addHours: add_hours, - addISOYears: add_iso_years, - addMilliseconds: add_milliseconds, - addMinutes: add_minutes, - addMonths: add_months, - addQuarters: add_quarters, - addSeconds: add_seconds, - addWeeks: add_weeks, - addYears: add_years, - areRangesOverlapping: are_ranges_overlapping, - closestIndexTo: closest_index_to, - closestTo: closest_to, - compareAsc: compare_asc, - compareDesc: compare_desc, - differenceInCalendarDays: difference_in_calendar_days, - differenceInCalendarISOWeeks: difference_in_calendar_iso_weeks, - differenceInCalendarISOYears: difference_in_calendar_iso_years, - differenceInCalendarMonths: difference_in_calendar_months, - differenceInCalendarQuarters: difference_in_calendar_quarters, - differenceInCalendarWeeks: difference_in_calendar_weeks, - differenceInCalendarYears: difference_in_calendar_years, - differenceInDays: difference_in_days, - differenceInHours: difference_in_hours, - differenceInISOYears: difference_in_iso_years, - differenceInMilliseconds: difference_in_milliseconds, - differenceInMinutes: difference_in_minutes, - differenceInMonths: difference_in_months, - differenceInQuarters: difference_in_quarters, - differenceInSeconds: difference_in_seconds, - differenceInWeeks: difference_in_weeks, - differenceInYears: difference_in_years, - distanceInWords: distance_in_words, - distanceInWordsStrict: distance_in_words_strict, - distanceInWordsToNow: distance_in_words_to_now, - eachDay: each_day, - endOfDay: end_of_day, - endOfHour: end_of_hour, - endOfISOWeek: end_of_iso_week, - endOfISOYear: end_of_iso_year, - endOfMinute: end_of_minute, - endOfMonth: end_of_month, - endOfQuarter: end_of_quarter, - endOfSecond: end_of_second, - endOfToday: end_of_today, - endOfTomorrow: end_of_tomorrow, - endOfWeek: end_of_week, - endOfYear: end_of_year, - endOfYesterday: end_of_yesterday, - format: format_1, - getDate: get_date, - getDay: get_day, - getDayOfYear: get_day_of_year, - getDaysInMonth: get_days_in_month, - getDaysInYear: get_days_in_year, - getHours: get_hours, - getISODay: get_iso_day, - getISOWeek: get_iso_week, - getISOWeeksInYear: get_iso_weeks_in_year, - getISOYear: get_iso_year, - getMilliseconds: get_milliseconds, - getMinutes: get_minutes, - getMonth: get_month, - getOverlappingDaysInRanges: get_overlapping_days_in_ranges, - getQuarter: get_quarter, - getSeconds: get_seconds, - getTime: get_time, - getYear: get_year, - isAfter: is_after, - isBefore: is_before, - isDate: is_date, - isEqual: is_equal, - isFirstDayOfMonth: is_first_day_of_month, - isFriday: is_friday, - isFuture: is_future, - isLastDayOfMonth: is_last_day_of_month, - isLeapYear: is_leap_year, - isMonday: is_monday, - isPast: is_past, - isSameDay: is_same_day, - isSameHour: is_same_hour, - isSameISOWeek: is_same_iso_week, - isSameISOYear: is_same_iso_year, - isSameMinute: is_same_minute, - isSameMonth: is_same_month, - isSameQuarter: is_same_quarter, - isSameSecond: is_same_second, - isSameWeek: is_same_week, - isSameYear: is_same_year, - isSaturday: is_saturday, - isSunday: is_sunday, - isThisHour: is_this_hour, - isThisISOWeek: is_this_iso_week, - isThisISOYear: is_this_iso_year, - isThisMinute: is_this_minute, - isThisMonth: is_this_month, - isThisQuarter: is_this_quarter, - isThisSecond: is_this_second, - isThisWeek: is_this_week, - isThisYear: is_this_year, - isThursday: is_thursday, - isToday: is_today, - isTomorrow: is_tomorrow, - isTuesday: is_tuesday, - isValid: is_valid, - isWednesday: is_wednesday, - isWeekend: is_weekend, - isWithinRange: is_within_range, - isYesterday: is_yesterday, - lastDayOfISOWeek: last_day_of_iso_week, - lastDayOfISOYear: last_day_of_iso_year, - lastDayOfMonth: last_day_of_month, - lastDayOfQuarter: last_day_of_quarter, - lastDayOfWeek: last_day_of_week, - lastDayOfYear: last_day_of_year, - max: max_1, - min: min_1, - parse: parse_1, - setDate: set_date, - setDay: set_day, - setDayOfYear: set_day_of_year, - setHours: set_hours, - setISODay: set_iso_day, - setISOWeek: set_iso_week, - setISOYear: set_iso_year, - setMilliseconds: set_milliseconds, - setMinutes: set_minutes, - setMonth: set_month, - setQuarter: set_quarter, - setSeconds: set_seconds, - setYear: set_year, - startOfDay: start_of_day, - startOfHour: start_of_hour, - startOfISOWeek: start_of_iso_week, - startOfISOYear: start_of_iso_year, - startOfMinute: start_of_minute, - startOfMonth: start_of_month, - startOfQuarter: start_of_quarter, - startOfSecond: start_of_second, - startOfToday: start_of_today, - startOfTomorrow: start_of_tomorrow, - startOfWeek: start_of_week, - startOfYear: start_of_year, - startOfYesterday: start_of_yesterday, - subDays: sub_days, - subHours: sub_hours, - subISOYears: sub_iso_years, - subMilliseconds: sub_milliseconds, - subMinutes: sub_minutes, - subMonths: sub_months, - subQuarters: sub_quarters, - subSeconds: sub_seconds, - subWeeks: sub_weeks, - subYears: sub_years -}; - -const user = "user"; - -const date$2 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); -const foo$2 = `Sunnyvale ${user} ${date$2}`; - -const date$1 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); -const foo$1 = `@foo/lib/a ${date$1}`; - -const date = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); -const foo = `@foo/lib/a/a/a ${date}`; - -const fum = 'Wonderland'; - -var hello = 'Hello'; - -const name = 'Alice'; - -const json_key = "json_value"; - -console.log( - `${hello}, ${name} in ${fum} ${foo$2} ${foo$1} ${foo} ${far_a} ${far_a_b_c} ${json_key}`); - -// Test for sequences = false -class A { - a() { - return document.a; - } -} -function inline_me() { - return 'abc'; -} -console.error(new A().a(), inline_me(), thing); - -export { A }; -//# sourceMappingURL=bundle.esm.js.map
diff --git a/packages/rollup/test/integration/golden.iife.js.map.sha256_ b/packages/rollup/test/integration/golden.iife.js.map.sha256_ deleted file mode 100644 index a390b18..0000000 --- a/packages/rollup/test/integration/golden.iife.js.map.sha256_ +++ /dev/null
@@ -1 +0,0 @@ -63b73c20a24b95236e87bd8c552976848cc581484dd053d27446ddd4fe006ab4 \ No newline at end of file
diff --git a/packages/rollup/test/integration/golden.iife.js_ b/packages/rollup/test/integration/golden.iife.js_ deleted file mode 100644 index 94bef77..0000000 --- a/packages/rollup/test/integration/golden.iife.js_ +++ /dev/null
@@ -1,5685 +0,0 @@ -/** - * @license A dummy license banner that goes at the top of the file. - * This is version <unknown> - */ - -var bundle = (function (exports, some_global_var) { - 'use strict'; - - var far_a = `@far/a`; - - var far_a_b_c = `@far/a/b/c`; - - var MILLISECONDS_IN_MINUTE$6 = 60000; - - /** - * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. - * They usually appear for dates that denote time before the timezones were introduced - * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 - * and GMT+01:00:00 after that date) - * - * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above, - * which would lead to incorrect calculations. - * - * This function returns the timezone offset in milliseconds that takes seconds in account. - */ - var getTimezoneOffsetInMilliseconds = function getTimezoneOffsetInMilliseconds (dirtyDate) { - var date = new Date(dirtyDate.getTime()); - var baseTimezoneOffset = date.getTimezoneOffset(); - date.setSeconds(0, 0); - var millisecondsPartOfTimezoneOffset = date.getTime() % MILLISECONDS_IN_MINUTE$6; - - return baseTimezoneOffset * MILLISECONDS_IN_MINUTE$6 + millisecondsPartOfTimezoneOffset - }; - - /** - * @category Common Helpers - * @summary Is the given argument an instance of Date? - * - * @description - * Is the given argument an instance of Date? - * - * @param {*} argument - the argument to check - * @returns {Boolean} the given argument is an instance of Date - * - * @example - * // Is 'mayonnaise' a Date? - * var result = isDate('mayonnaise') - * //=> false - */ - function isDate (argument) { - return argument instanceof Date - } - - var is_date = isDate; - - var MILLISECONDS_IN_HOUR$2 = 3600000; - var MILLISECONDS_IN_MINUTE$5 = 60000; - var DEFAULT_ADDITIONAL_DIGITS = 2; - - var parseTokenDateTimeDelimeter = /[T ]/; - var parseTokenPlainTime = /:/; - - // year tokens - var parseTokenYY = /^(\d{2})$/; - var parseTokensYYY = [ - /^([+-]\d{2})$/, // 0 additional digits - /^([+-]\d{3})$/, // 1 additional digit - /^([+-]\d{4})$/ // 2 additional digits - ]; - - var parseTokenYYYY = /^(\d{4})/; - var parseTokensYYYYY = [ - /^([+-]\d{4})/, // 0 additional digits - /^([+-]\d{5})/, // 1 additional digit - /^([+-]\d{6})/ // 2 additional digits - ]; - - // date tokens - var parseTokenMM = /^-(\d{2})$/; - var parseTokenDDD = /^-?(\d{3})$/; - var parseTokenMMDD = /^-?(\d{2})-?(\d{2})$/; - var parseTokenWww = /^-?W(\d{2})$/; - var parseTokenWwwD = /^-?W(\d{2})-?(\d{1})$/; - - // time tokens - var parseTokenHH = /^(\d{2}([.,]\d*)?)$/; - var parseTokenHHMM = /^(\d{2}):?(\d{2}([.,]\d*)?)$/; - var parseTokenHHMMSS = /^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/; - - // timezone tokens - var parseTokenTimezone = /([Z+-].*)$/; - var parseTokenTimezoneZ = /^(Z)$/; - var parseTokenTimezoneHH = /^([+-])(\d{2})$/; - var parseTokenTimezoneHHMM = /^([+-])(\d{2}):?(\d{2})$/; - - /** - * @category Common Helpers - * @summary Convert the given argument to an instance of Date. - * - * @description - * Convert the given argument to an instance of Date. - * - * If the argument is an instance of Date, the function returns its clone. - * - * If the argument is a number, it is treated as a timestamp. - * - * If an argument is a string, the function tries to parse it. - * Function accepts complete ISO 8601 formats as well as partial implementations. - * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 - * - * If all above fails, the function passes the given argument to Date constructor. - * - * @param {Date|String|Number} argument - the value to convert - * @param {Object} [options] - the object with options - * @param {0 | 1 | 2} [options.additionalDigits=2] - the additional number of digits in the extended year format - * @returns {Date} the parsed date in the local time zone - * - * @example - * // Convert string '2014-02-11T11:30:30' to date: - * var result = parse('2014-02-11T11:30:30') - * //=> Tue Feb 11 2014 11:30:30 - * - * @example - * // Parse string '+02014101', - * // if the additional number of digits in the extended year format is 1: - * var result = parse('+02014101', {additionalDigits: 1}) - * //=> Fri Apr 11 2014 00:00:00 - */ - function parse (argument, dirtyOptions) { - if (is_date(argument)) { - // Prevent the date to lose the milliseconds when passed to new Date() in IE10 - return new Date(argument.getTime()) - } else if (typeof argument !== 'string') { - return new Date(argument) - } - - var options = dirtyOptions || {}; - var additionalDigits = options.additionalDigits; - if (additionalDigits == null) { - additionalDigits = DEFAULT_ADDITIONAL_DIGITS; - } else { - additionalDigits = Number(additionalDigits); - } - - var dateStrings = splitDateString(argument); - - var parseYearResult = parseYear(dateStrings.date, additionalDigits); - var year = parseYearResult.year; - var restDateString = parseYearResult.restDateString; - - var date = parseDate(restDateString, year); - - if (date) { - var timestamp = date.getTime(); - var time = 0; - var offset; - - if (dateStrings.time) { - time = parseTime(dateStrings.time); - } - - if (dateStrings.timezone) { - offset = parseTimezone(dateStrings.timezone) * MILLISECONDS_IN_MINUTE$5; - } else { - var fullTime = timestamp + time; - var fullTimeDate = new Date(fullTime); - - offset = getTimezoneOffsetInMilliseconds(fullTimeDate); - - // Adjust time when it's coming from DST - var fullTimeDateNextDay = new Date(fullTime); - fullTimeDateNextDay.setDate(fullTimeDate.getDate() + 1); - var offsetDiff = - getTimezoneOffsetInMilliseconds(fullTimeDateNextDay) - - getTimezoneOffsetInMilliseconds(fullTimeDate); - if (offsetDiff > 0) { - offset += offsetDiff; - } - } - - return new Date(timestamp + time + offset) - } else { - return new Date(argument) - } - } - - function splitDateString (dateString) { - var dateStrings = {}; - var array = dateString.split(parseTokenDateTimeDelimeter); - var timeString; - - if (parseTokenPlainTime.test(array[0])) { - dateStrings.date = null; - timeString = array[0]; - } else { - dateStrings.date = array[0]; - timeString = array[1]; - } - - if (timeString) { - var token = parseTokenTimezone.exec(timeString); - if (token) { - dateStrings.time = timeString.replace(token[1], ''); - dateStrings.timezone = token[1]; - } else { - dateStrings.time = timeString; - } - } - - return dateStrings - } - - function parseYear (dateString, additionalDigits) { - var parseTokenYYY = parseTokensYYY[additionalDigits]; - var parseTokenYYYYY = parseTokensYYYYY[additionalDigits]; - - var token; - - // YYYY or ±YYYYY - token = parseTokenYYYY.exec(dateString) || parseTokenYYYYY.exec(dateString); - if (token) { - var yearString = token[1]; - return { - year: parseInt(yearString, 10), - restDateString: dateString.slice(yearString.length) - } - } - - // YY or ±YYY - token = parseTokenYY.exec(dateString) || parseTokenYYY.exec(dateString); - if (token) { - var centuryString = token[1]; - return { - year: parseInt(centuryString, 10) * 100, - restDateString: dateString.slice(centuryString.length) - } - } - - // Invalid ISO-formatted year - return { - year: null - } - } - - function parseDate (dateString, year) { - // Invalid ISO-formatted year - if (year === null) { - return null - } - - var token; - var date; - var month; - var week; - - // YYYY - if (dateString.length === 0) { - date = new Date(0); - date.setUTCFullYear(year); - return date - } - - // YYYY-MM - token = parseTokenMM.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - date.setUTCFullYear(year, month); - return date - } - - // YYYY-DDD or YYYYDDD - token = parseTokenDDD.exec(dateString); - if (token) { - date = new Date(0); - var dayOfYear = parseInt(token[1], 10); - date.setUTCFullYear(year, 0, dayOfYear); - return date - } - - // YYYY-MM-DD or YYYYMMDD - token = parseTokenMMDD.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - var day = parseInt(token[2], 10); - date.setUTCFullYear(year, month, day); - return date - } - - // YYYY-Www or YYYYWww - token = parseTokenWww.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - return dayOfISOYear(year, week) - } - - // YYYY-Www-D or YYYYWwwD - token = parseTokenWwwD.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - var dayOfWeek = parseInt(token[2], 10) - 1; - return dayOfISOYear(year, week, dayOfWeek) - } - - // Invalid ISO-formatted date - return null - } - - function parseTime (timeString) { - var token; - var hours; - var minutes; - - // hh - token = parseTokenHH.exec(timeString); - if (token) { - hours = parseFloat(token[1].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 - } - - // hh:mm or hhmm - token = parseTokenHHMM.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseFloat(token[2].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 - } - - // hh:mm:ss or hhmmss - token = parseTokenHHMMSS.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseInt(token[2], 10); - var seconds = parseFloat(token[3].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 + - seconds * 1000 - } - - // Invalid ISO-formatted time - return null - } - - function parseTimezone (timezoneString) { - var token; - var absoluteOffset; - - // Z - token = parseTokenTimezoneZ.exec(timezoneString); - if (token) { - return 0 - } - - // ±hh - token = parseTokenTimezoneHH.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60; - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - // ±hh:mm or ±hhmm - token = parseTokenTimezoneHHMM.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60 + parseInt(token[3], 10); - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - return 0 - } - - function dayOfISOYear (isoYear, week, day) { - week = week || 0; - day = day || 0; - var date = new Date(0); - date.setUTCFullYear(isoYear, 0, 4); - var fourthOfJanuaryDay = date.getUTCDay() || 7; - var diff = week * 7 + day + 1 - fourthOfJanuaryDay; - date.setUTCDate(date.getUTCDate() + diff); - return date - } - - var parse_1 = parse; - - /** - * @category Day Helpers - * @summary Add the specified number of days to the given date. - * - * @description - * Add the specified number of days to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be added - * @returns {Date} the new date with the days added - * - * @example - * // Add 10 days to 1 September 2014: - * var result = addDays(new Date(2014, 8, 1), 10) - * //=> Thu Sep 11 2014 00:00:00 - */ - function addDays (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - date.setDate(date.getDate() + amount); - return date - } - - var add_days = addDays; - - /** - * @category Millisecond Helpers - * @summary Add the specified number of milliseconds to the given date. - * - * @description - * Add the specified number of milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be added - * @returns {Date} the new date with the milliseconds added - * - * @example - * // Add 750 milliseconds to 10 July 2014 12:45:30.000: - * var result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:30.750 - */ - function addMilliseconds (dirtyDate, dirtyAmount) { - var timestamp = parse_1(dirtyDate).getTime(); - var amount = Number(dirtyAmount); - return new Date(timestamp + amount) - } - - var add_milliseconds = addMilliseconds; - - var MILLISECONDS_IN_HOUR$1 = 3600000; - - /** - * @category Hour Helpers - * @summary Add the specified number of hours to the given date. - * - * @description - * Add the specified number of hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be added - * @returns {Date} the new date with the hours added - * - * @example - * // Add 2 hours to 10 July 2014 23:00:00: - * var result = addHours(new Date(2014, 6, 10, 23, 0), 2) - * //=> Fri Jul 11 2014 01:00:00 - */ - function addHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR$1) - } - - var add_hours = addHours; - - /** - * @category Week Helpers - * @summary Return the start of a week for the given date. - * - * @description - * Return the start of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the start of a week - * - * @example - * // The start of a week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - - date.setDate(date.getDate() - diff); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_week = startOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the start of an ISO week for the given date. - * - * @description - * Return the start of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO week - * - * @example - * // The start of an ISO week for 2 September 2014 11:55:00: - * var result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfISOWeek (dirtyDate) { - return start_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var start_of_iso_week = startOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the ISO week-numbering year of the given date. - * - * @description - * Get the ISO week-numbering year of the given date, - * which always starts 3 days before the year's first Thursday. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week-numbering year - * - * @example - * // Which ISO-week numbering year is 2 January 2005? - * var result = getISOYear(new Date(2005, 0, 2)) - * //=> 2004 - */ - function getISOYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var startOfNextYear = start_of_iso_week(fourthOfJanuaryOfNextYear); - - var fourthOfJanuaryOfThisYear = new Date(0); - fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); - fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); - var startOfThisYear = start_of_iso_week(fourthOfJanuaryOfThisYear); - - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1 - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year - } else { - return year - 1 - } - } - - var get_iso_year = getISOYear; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the start of an ISO week-numbering year for the given date. - * - * @description - * Return the start of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO year - * - * @example - * // The start of an ISO week-numbering year for 2 July 2005: - * var result = startOfISOYear(new Date(2005, 6, 2)) - * //=> Mon Jan 03 2005 00:00:00 - */ - function startOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - return date - } - - var start_of_iso_year = startOfISOYear; - - /** - * @category Day Helpers - * @summary Return the start of a day for the given date. - * - * @description - * Return the start of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a day - * - * @example - * // The start of a day for 2 September 2014 11:55:00: - * var result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 00:00:00 - */ - function startOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_day = startOfDay; - - var MILLISECONDS_IN_MINUTE$4 = 60000; - var MILLISECONDS_IN_DAY$1 = 86400000; - - /** - * @category Day Helpers - * @summary Get the number of calendar days between the given dates. - * - * @description - * Get the number of calendar days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar days - * - * @example - * // How many calendar days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInCalendarDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 366 - */ - function differenceInCalendarDays (dirtyDateLeft, dirtyDateRight) { - var startOfDayLeft = start_of_day(dirtyDateLeft); - var startOfDayRight = start_of_day(dirtyDateRight); - - var timestampLeft = startOfDayLeft.getTime() - - startOfDayLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - var timestampRight = startOfDayRight.getTime() - - startOfDayRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a day is not constant - // (e.g. it's different in the day of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY$1) - } - - var difference_in_calendar_days = differenceInCalendarDays; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Set the ISO week-numbering year to the given date. - * - * @description - * Set the ISO week-numbering year to the given date, - * saving the week number and the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoYear - the ISO week-numbering year of the new date - * @returns {Date} the new date with the ISO week-numbering year setted - * - * @example - * // Set ISO week-numbering year 2007 to 29 December 2008: - * var result = setISOYear(new Date(2008, 11, 29), 2007) - * //=> Mon Jan 01 2007 00:00:00 - */ - function setISOYear (dirtyDate, dirtyISOYear) { - var date = parse_1(dirtyDate); - var isoYear = Number(dirtyISOYear); - var diff = difference_in_calendar_days(date, start_of_iso_year(date)); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(isoYear, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - date = start_of_iso_year(fourthOfJanuary); - date.setDate(date.getDate() + diff); - return date - } - - var set_iso_year = setISOYear; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Add the specified number of ISO week-numbering years to the given date. - * - * @description - * Add the specified number of ISO week-numbering years to the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be added - * @returns {Date} the new date with the ISO week-numbering years added - * - * @example - * // Add 5 ISO week-numbering years to 2 July 2010: - * var result = addISOYears(new Date(2010, 6, 2), 5) - * //=> Fri Jun 26 2015 00:00:00 - */ - function addISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return set_iso_year(dirtyDate, get_iso_year(dirtyDate) + amount) - } - - var add_iso_years = addISOYears; - - var MILLISECONDS_IN_MINUTE$3 = 60000; - - /** - * @category Minute Helpers - * @summary Add the specified number of minutes to the given date. - * - * @description - * Add the specified number of minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be added - * @returns {Date} the new date with the minutes added - * - * @example - * // Add 30 minutes to 10 July 2014 12:00:00: - * var result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 12:30:00 - */ - function addMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE$3) - } - - var add_minutes = addMinutes; - - /** - * @category Month Helpers - * @summary Get the number of days in a month of the given date. - * - * @description - * Get the number of days in a month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a month - * - * @example - * // How many days are in February 2000? - * var result = getDaysInMonth(new Date(2000, 1)) - * //=> 29 - */ - function getDaysInMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - var monthIndex = date.getMonth(); - var lastDayOfMonth = new Date(0); - lastDayOfMonth.setFullYear(year, monthIndex + 1, 0); - lastDayOfMonth.setHours(0, 0, 0, 0); - return lastDayOfMonth.getDate() - } - - var get_days_in_month = getDaysInMonth; - - /** - * @category Month Helpers - * @summary Add the specified number of months to the given date. - * - * @description - * Add the specified number of months to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be added - * @returns {Date} the new date with the months added - * - * @example - * // Add 5 months to 1 September 2014: - * var result = addMonths(new Date(2014, 8, 1), 5) - * //=> Sun Feb 01 2015 00:00:00 - */ - function addMonths (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - var desiredMonth = date.getMonth() + amount; - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(date.getFullYear(), desiredMonth, 1); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(desiredMonth, Math.min(daysInMonth, date.getDate())); - return date - } - - var add_months = addMonths; - - /** - * @category Quarter Helpers - * @summary Add the specified number of year quarters to the given date. - * - * @description - * Add the specified number of year quarters to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be added - * @returns {Date} the new date with the quarters added - * - * @example - * // Add 1 quarter to 1 September 2014: - * var result = addQuarters(new Date(2014, 8, 1), 1) - * //=> Mon Dec 01 2014 00:00:00 - */ - function addQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var months = amount * 3; - return add_months(dirtyDate, months) - } - - var add_quarters = addQuarters; - - /** - * @category Second Helpers - * @summary Add the specified number of seconds to the given date. - * - * @description - * Add the specified number of seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be added - * @returns {Date} the new date with the seconds added - * - * @example - * // Add 30 seconds to 10 July 2014 12:45:00: - * var result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:45:30 - */ - function addSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * 1000) - } - - var add_seconds = addSeconds; - - /** - * @category Week Helpers - * @summary Add the specified number of weeks to the given date. - * - * @description - * Add the specified number of week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be added - * @returns {Date} the new date with the weeks added - * - * @example - * // Add 4 weeks to 1 September 2014: - * var result = addWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Sep 29 2014 00:00:00 - */ - function addWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var days = amount * 7; - return add_days(dirtyDate, days) - } - - var add_weeks = addWeeks; - - /** - * @category Year Helpers - * @summary Add the specified number of years to the given date. - * - * @description - * Add the specified number of years to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be added - * @returns {Date} the new date with the years added - * - * @example - * // Add 5 years to 1 September 2014: - * var result = addYears(new Date(2014, 8, 1), 5) - * //=> Sun Sep 01 2019 00:00:00 - */ - function addYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, amount * 12) - } - - var add_years = addYears; - - /** - * @category Range Helpers - * @summary Is the given date range overlapping with another date range? - * - * @description - * Is the given date range overlapping with another date range? - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Boolean} whether the date ranges are overlapping - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> true - * - * @example - * // For non-overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> false - */ - function areRangesOverlapping (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return initialStartTime < comparedEndTime && comparedStartTime < initialEndTime - } - - var are_ranges_overlapping = areRangesOverlapping; - - /** - * @category Common Helpers - * @summary Return an index of the closest date from the array comparing to the given date. - * - * @description - * Return an index of the closest date from the array comparing to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Number} an index of the date closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015? - * var dateToCompare = new Date(2015, 8, 6) - * var datesArray = [ - * new Date(2015, 0, 1), - * new Date(2016, 0, 1), - * new Date(2017, 0, 1) - * ] - * var result = closestIndexTo(dateToCompare, datesArray) - * //=> 1 - */ - function closestIndexTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate, index) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = index; - minDistance = distance; - } - }); - - return result - } - - var closest_index_to = closestIndexTo; - - /** - * @category Common Helpers - * @summary Return a date from the array closest to the given date. - * - * @description - * Return a date from the array closest to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Date} the date from the array closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030? - * var dateToCompare = new Date(2015, 8, 6) - * var result = closestTo(dateToCompare, [ - * new Date(2000, 0, 1), - * new Date(2030, 0, 1) - * ]) - * //=> Tue Jan 01 2030 00:00:00 - */ - function closestTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = currentDate; - minDistance = distance; - } - }); - - return result - } - - var closest_to = closestTo; - - /** - * @category Common Helpers - * @summary Compare the two dates and return -1, 0 or 1. - * - * @description - * Compare the two dates and return 1 if the first date is after the second, - * -1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989: - * var result = compareAsc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> -1 - * - * @example - * // Sort the array of dates: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareAsc) - * //=> [ - * // Wed Feb 11 1987 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Sun Jul 02 1995 00:00:00 - * // ] - */ - function compareAsc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft < timeRight) { - return -1 - } else if (timeLeft > timeRight) { - return 1 - } else { - return 0 - } - } - - var compare_asc = compareAsc; - - /** - * @category Common Helpers - * @summary Compare the two dates reverse chronologically and return -1, 0 or 1. - * - * @description - * Compare the two dates and return -1 if the first date is after the second, - * 1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989 reverse chronologically: - * var result = compareDesc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> 1 - * - * @example - * // Sort the array of dates in reverse chronological order: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareDesc) - * //=> [ - * // Sun Jul 02 1995 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Wed Feb 11 1987 00:00:00 - * // ] - */ - function compareDesc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft > timeRight) { - return -1 - } else if (timeLeft < timeRight) { - return 1 - } else { - return 0 - } - } - - var compare_desc = compareDesc; - - var MILLISECONDS_IN_MINUTE$2 = 60000; - var MILLISECONDS_IN_WEEK$3 = 604800000; - - /** - * @category ISO Week Helpers - * @summary Get the number of calendar ISO weeks between the given dates. - * - * @description - * Get the number of calendar ISO weeks between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO weeks - * - * @example - * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014? - * var result = differenceInCalendarISOWeeks( - * new Date(2014, 6, 21), - * new Date(2014, 6, 6) - * ) - * //=> 3 - */ - function differenceInCalendarISOWeeks (dirtyDateLeft, dirtyDateRight) { - var startOfISOWeekLeft = start_of_iso_week(dirtyDateLeft); - var startOfISOWeekRight = start_of_iso_week(dirtyDateRight); - - var timestampLeft = startOfISOWeekLeft.getTime() - - startOfISOWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - var timestampRight = startOfISOWeekRight.getTime() - - startOfISOWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$3) - } - - var difference_in_calendar_iso_weeks = differenceInCalendarISOWeeks; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of calendar ISO week-numbering years between the given dates. - * - * @description - * Get the number of calendar ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO week-numbering years - * - * @example - * // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012? - * var result = differenceInCalendarISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 2 - */ - function differenceInCalendarISOYears (dirtyDateLeft, dirtyDateRight) { - return get_iso_year(dirtyDateLeft) - get_iso_year(dirtyDateRight) - } - - var difference_in_calendar_iso_years = differenceInCalendarISOYears; - - /** - * @category Month Helpers - * @summary Get the number of calendar months between the given dates. - * - * @description - * Get the number of calendar months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar months - * - * @example - * // How many calendar months are between 31 January 2014 and 1 September 2014? - * var result = differenceInCalendarMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 8 - */ - function differenceInCalendarMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); - - return yearDiff * 12 + monthDiff - } - - var difference_in_calendar_months = differenceInCalendarMonths; - - /** - * @category Quarter Helpers - * @summary Get the year quarter of the given date. - * - * @description - * Get the year quarter of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the quarter - * - * @example - * // Which quarter is 2 July 2014? - * var result = getQuarter(new Date(2014, 6, 2)) - * //=> 3 - */ - function getQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var quarter = Math.floor(date.getMonth() / 3) + 1; - return quarter - } - - var get_quarter = getQuarter; - - /** - * @category Quarter Helpers - * @summary Get the number of calendar quarters between the given dates. - * - * @description - * Get the number of calendar quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar quarters - * - * @example - * // How many calendar quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInCalendarQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 3 - */ - function differenceInCalendarQuarters (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var quarterDiff = get_quarter(dateLeft) - get_quarter(dateRight); - - return yearDiff * 4 + quarterDiff - } - - var difference_in_calendar_quarters = differenceInCalendarQuarters; - - var MILLISECONDS_IN_MINUTE$1 = 60000; - var MILLISECONDS_IN_WEEK$2 = 604800000; - - /** - * @category Week Helpers - * @summary Get the number of calendar weeks between the given dates. - * - * @description - * Get the number of calendar weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Number} the number of calendar weeks - * - * @example - * // How many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 3 - * - * @example - * // If the week starts on Monday, - * // how many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5), - * {weekStartsOn: 1} - * ) - * //=> 2 - */ - function differenceInCalendarWeeks (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var startOfWeekLeft = start_of_week(dirtyDateLeft, dirtyOptions); - var startOfWeekRight = start_of_week(dirtyDateRight, dirtyOptions); - - var timestampLeft = startOfWeekLeft.getTime() - - startOfWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - var timestampRight = startOfWeekRight.getTime() - - startOfWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$2) - } - - var difference_in_calendar_weeks = differenceInCalendarWeeks; - - /** - * @category Year Helpers - * @summary Get the number of calendar years between the given dates. - * - * @description - * Get the number of calendar years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar years - * - * @example - * // How many calendar years are between 31 December 2013 and 11 February 2015? - * var result = differenceInCalendarYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ - function differenceInCalendarYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - return dateLeft.getFullYear() - dateRight.getFullYear() - } - - var difference_in_calendar_years = differenceInCalendarYears; - - /** - * @category Day Helpers - * @summary Get the number of full days between the given dates. - * - * @description - * Get the number of full days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full days - * - * @example - * // How many full days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 365 - */ - function differenceInDays (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_days(dateLeft, dateRight)); - dateLeft.setDate(dateLeft.getDate() - sign * difference); - - // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full - // If so, result must be decreased by 1 in absolute value - var isLastDayNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastDayNotFull) - } - - var difference_in_days = differenceInDays; - - /** - * @category Millisecond Helpers - * @summary Get the number of milliseconds between the given dates. - * - * @description - * Get the number of milliseconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of milliseconds - * - * @example - * // How many milliseconds are between - * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700? - * var result = differenceInMilliseconds( - * new Date(2014, 6, 2, 12, 30, 21, 700), - * new Date(2014, 6, 2, 12, 30, 20, 600) - * ) - * //=> 1100 - */ - function differenceInMilliseconds (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getTime() - dateRight.getTime() - } - - var difference_in_milliseconds = differenceInMilliseconds; - - var MILLISECONDS_IN_HOUR = 3600000; - - /** - * @category Hour Helpers - * @summary Get the number of hours between the given dates. - * - * @description - * Get the number of hours between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of hours - * - * @example - * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00? - * var result = differenceInHours( - * new Date(2014, 6, 2, 19, 0), - * new Date(2014, 6, 2, 6, 50) - * ) - * //=> 12 - */ - function differenceInHours (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_hours = differenceInHours; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Subtract the specified number of ISO week-numbering years from the given date. - * - * @description - * Subtract the specified number of ISO week-numbering years from the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be subtracted - * @returns {Date} the new date with the ISO week-numbering years subtracted - * - * @example - * // Subtract 5 ISO week-numbering years from 1 September 2014: - * var result = subISOYears(new Date(2014, 8, 1), 5) - * //=> Mon Aug 31 2009 00:00:00 - */ - function subISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_iso_years(dirtyDate, -amount) - } - - var sub_iso_years = subISOYears; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of full ISO week-numbering years between the given dates. - * - * @description - * Get the number of full ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full ISO week-numbering years - * - * @example - * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012? - * var result = differenceInISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 1 - */ - function differenceInISOYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_iso_years(dateLeft, dateRight)); - dateLeft = sub_iso_years(dateLeft, sign * difference); - - // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1 - // if last calendar ISO year is not full - // If so, result must be decreased by 1 in absolute value - var isLastISOYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastISOYearNotFull) - } - - var difference_in_iso_years = differenceInISOYears; - - var MILLISECONDS_IN_MINUTE = 60000; - - /** - * @category Minute Helpers - * @summary Get the number of minutes between the given dates. - * - * @description - * Get the number of minutes between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of minutes - * - * @example - * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00? - * var result = differenceInMinutes( - * new Date(2014, 6, 2, 12, 20, 0), - * new Date(2014, 6, 2, 12, 7, 59) - * ) - * //=> 12 - */ - function differenceInMinutes (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_minutes = differenceInMinutes; - - /** - * @category Month Helpers - * @summary Get the number of full months between the given dates. - * - * @description - * Get the number of full months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full months - * - * @example - * // How many full months are between 31 January 2014 and 1 September 2014? - * var result = differenceInMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 7 - */ - function differenceInMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_months(dateLeft, dateRight)); - dateLeft.setMonth(dateLeft.getMonth() - sign * difference); - - // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full - // If so, result must be decreased by 1 in absolute value - var isLastMonthNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastMonthNotFull) - } - - var difference_in_months = differenceInMonths; - - /** - * @category Quarter Helpers - * @summary Get the number of full quarters between the given dates. - * - * @description - * Get the number of full quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full quarters - * - * @example - * // How many full quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ - function differenceInQuarters (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_months(dirtyDateLeft, dirtyDateRight) / 3; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_quarters = differenceInQuarters; - - /** - * @category Second Helpers - * @summary Get the number of seconds between the given dates. - * - * @description - * Get the number of seconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of seconds - * - * @example - * // How many seconds are between - * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000? - * var result = differenceInSeconds( - * new Date(2014, 6, 2, 12, 30, 20, 0), - * new Date(2014, 6, 2, 12, 30, 7, 999) - * ) - * //=> 12 - */ - function differenceInSeconds (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / 1000; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_seconds = differenceInSeconds; - - /** - * @category Week Helpers - * @summary Get the number of full weeks between the given dates. - * - * @description - * Get the number of full weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full weeks - * - * @example - * // How many full weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 2 - */ - function differenceInWeeks (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_days(dirtyDateLeft, dirtyDateRight) / 7; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_weeks = differenceInWeeks; - - /** - * @category Year Helpers - * @summary Get the number of full years between the given dates. - * - * @description - * Get the number of full years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full years - * - * @example - * // How many full years are between 31 December 2013 and 11 February 2015? - * var result = differenceInYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 1 - */ - function differenceInYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_years(dateLeft, dateRight)); - dateLeft.setFullYear(dateLeft.getFullYear() - sign * difference); - - // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full - // If so, result must be decreased by 1 in absolute value - var isLastYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastYearNotFull) - } - - var difference_in_years = differenceInYears; - - function buildDistanceInWordsLocale () { - var distanceInWordsLocale = { - lessThanXSeconds: { - one: 'less than a second', - other: 'less than {{count}} seconds' - }, - - xSeconds: { - one: '1 second', - other: '{{count}} seconds' - }, - - halfAMinute: 'half a minute', - - lessThanXMinutes: { - one: 'less than a minute', - other: 'less than {{count}} minutes' - }, - - xMinutes: { - one: '1 minute', - other: '{{count}} minutes' - }, - - aboutXHours: { - one: 'about 1 hour', - other: 'about {{count}} hours' - }, - - xHours: { - one: '1 hour', - other: '{{count}} hours' - }, - - xDays: { - one: '1 day', - other: '{{count}} days' - }, - - aboutXMonths: { - one: 'about 1 month', - other: 'about {{count}} months' - }, - - xMonths: { - one: '1 month', - other: '{{count}} months' - }, - - aboutXYears: { - one: 'about 1 year', - other: 'about {{count}} years' - }, - - xYears: { - one: '1 year', - other: '{{count}} years' - }, - - overXYears: { - one: 'over 1 year', - other: 'over {{count}} years' - }, - - almostXYears: { - one: 'almost 1 year', - other: 'almost {{count}} years' - } - }; - - function localize (token, count, options) { - options = options || {}; - - var result; - if (typeof distanceInWordsLocale[token] === 'string') { - result = distanceInWordsLocale[token]; - } else if (count === 1) { - result = distanceInWordsLocale[token].one; - } else { - result = distanceInWordsLocale[token].other.replace('{{count}}', count); - } - - if (options.addSuffix) { - if (options.comparison > 0) { - return 'in ' + result - } else { - return result + ' ago' - } - } - - return result - } - - return { - localize: localize - } - } - - var build_distance_in_words_locale = buildDistanceInWordsLocale; - - var commonFormatterKeys = [ - 'M', 'MM', 'Q', 'D', 'DD', 'DDD', 'DDDD', 'd', - 'E', 'W', 'WW', 'YY', 'YYYY', 'GG', 'GGGG', - 'H', 'HH', 'h', 'hh', 'm', 'mm', - 's', 'ss', 'S', 'SS', 'SSS', - 'Z', 'ZZ', 'X', 'x' - ]; - - function buildFormattingTokensRegExp (formatters) { - var formatterKeys = []; - for (var key in formatters) { - if (formatters.hasOwnProperty(key)) { - formatterKeys.push(key); - } - } - - var formattingTokens = commonFormatterKeys - .concat(formatterKeys) - .sort() - .reverse(); - var formattingTokensRegExp = new RegExp( - '(\\[[^\\[]*\\])|(\\\\)?' + '(' + formattingTokens.join('|') + '|.)', 'g' - ); - - return formattingTokensRegExp - } - - var build_formatting_tokens_reg_exp = buildFormattingTokensRegExp; - - function buildFormatLocale () { - // Note: in English, the names of days of the week and months are capitalized. - // If you are making a new locale based on this one, check if the same is true for the language you're working on. - // Generally, formatted dates should look like they are in the middle of a sentence, - // e.g. in Spanish language the weekdays and months should be in the lowercase. - var months3char = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var monthsFull = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; - var weekdays2char = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']; - var weekdays3char = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - var weekdaysFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; - var meridiemUppercase = ['AM', 'PM']; - var meridiemLowercase = ['am', 'pm']; - var meridiemFull = ['a.m.', 'p.m.']; - - var formatters = { - // Month: Jan, Feb, ..., Dec - 'MMM': function (date) { - return months3char[date.getMonth()] - }, - - // Month: January, February, ..., December - 'MMMM': function (date) { - return monthsFull[date.getMonth()] - }, - - // Day of week: Su, Mo, ..., Sa - 'dd': function (date) { - return weekdays2char[date.getDay()] - }, - - // Day of week: Sun, Mon, ..., Sat - 'ddd': function (date) { - return weekdays3char[date.getDay()] - }, - - // Day of week: Sunday, Monday, ..., Saturday - 'dddd': function (date) { - return weekdaysFull[date.getDay()] - }, - - // AM, PM - 'A': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemUppercase[1] : meridiemUppercase[0] - }, - - // am, pm - 'a': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemLowercase[1] : meridiemLowercase[0] - }, - - // a.m., p.m. - 'aa': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemFull[1] : meridiemFull[0] - } - }; - - // Generate ordinal version of formatters: M -> Mo, D -> Do, etc. - var ordinalFormatters = ['M', 'D', 'DDD', 'd', 'Q', 'W']; - ordinalFormatters.forEach(function (formatterToken) { - formatters[formatterToken + 'o'] = function (date, formatters) { - return ordinal(formatters[formatterToken](date)) - }; - }); - - return { - formatters: formatters, - formattingTokensRegExp: build_formatting_tokens_reg_exp(formatters) - } - } - - function ordinal (number) { - var rem100 = number % 100; - if (rem100 > 20 || rem100 < 10) { - switch (rem100 % 10) { - case 1: - return number + 'st' - case 2: - return number + 'nd' - case 3: - return number + 'rd' - } - } - return number + 'th' - } - - var build_format_locale = buildFormatLocale; - - /** - * @category Locales - * @summary English locale. - */ - var en = { - distanceInWords: build_distance_in_words_locale(), - format: build_format_locale() - }; - - var MINUTES_IN_DAY$1 = 1440; - var MINUTES_IN_ALMOST_TWO_DAYS = 2520; - var MINUTES_IN_MONTH$1 = 43200; - var MINUTES_IN_TWO_MONTHS = 86400; - - /** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words. - * - * | Distance between dates | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance between dates | Result | - * |------------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWords( - * new Date(2014, 6, 2), - * new Date(2015, 0, 1) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00, including seconds? - * var result = distanceInWords( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWords( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> 'about 1 year ago' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWords( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ - function distanceInWords (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = Math.round(seconds / 60) - offset; - var months; - - // 0 up to 2 mins - if (minutes < 2) { - if (options.includeSeconds) { - if (seconds < 5) { - return localize('lessThanXSeconds', 5, localizeOptions) - } else if (seconds < 10) { - return localize('lessThanXSeconds', 10, localizeOptions) - } else if (seconds < 20) { - return localize('lessThanXSeconds', 20, localizeOptions) - } else if (seconds < 40) { - return localize('halfAMinute', null, localizeOptions) - } else if (seconds < 60) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', 1, localizeOptions) - } - } else { - if (minutes === 0) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', minutes, localizeOptions) - } - } - - // 2 mins up to 0.75 hrs - } else if (minutes < 45) { - return localize('xMinutes', minutes, localizeOptions) - - // 0.75 hrs up to 1.5 hrs - } else if (minutes < 90) { - return localize('aboutXHours', 1, localizeOptions) - - // 1.5 hrs up to 24 hrs - } else if (minutes < MINUTES_IN_DAY$1) { - var hours = Math.round(minutes / 60); - return localize('aboutXHours', hours, localizeOptions) - - // 1 day up to 1.75 days - } else if (minutes < MINUTES_IN_ALMOST_TWO_DAYS) { - return localize('xDays', 1, localizeOptions) - - // 1.75 days up to 30 days - } else if (minutes < MINUTES_IN_MONTH$1) { - var days = Math.round(minutes / MINUTES_IN_DAY$1); - return localize('xDays', days, localizeOptions) - - // 1 month up to 2 months - } else if (minutes < MINUTES_IN_TWO_MONTHS) { - months = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('aboutXMonths', months, localizeOptions) - } - - months = difference_in_months(dateRight, dateLeft); - - // 2 months up to 12 months - if (months < 12) { - var nearestMonth = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('xMonths', nearestMonth, localizeOptions) - - // 1 year up to max Date - } else { - var monthsSinceStartOfYear = months % 12; - var years = Math.floor(months / 12); - - // N years up to 1 years 3 months - if (monthsSinceStartOfYear < 3) { - return localize('aboutXYears', years, localizeOptions) - - // N years 3 months up to N years 9 months - } else if (monthsSinceStartOfYear < 9) { - return localize('overXYears', years, localizeOptions) - - // N years 9 months up to N year 12 months - } else { - return localize('almostXYears', years + 1, localizeOptions) - } - } - } - - var distance_in_words = distanceInWords; - - var MINUTES_IN_DAY = 1440; - var MINUTES_IN_MONTH = 43200; - var MINUTES_IN_YEAR = 525600; - - /** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words, using strict units. - * This is like `distanceInWords`, but does not use helpers like 'almost', 'over', - * 'less than' and the like. - * - * | Distance between dates | Result | - * |------------------------|---------------------| - * | 0 ... 59 secs | [0..59] seconds | - * | 1 ... 59 mins | [1..59] minutes | - * | 1 ... 23 hrs | [1..23] hours | - * | 1 ... 29 days | [1..29] days | - * | 1 ... 11 months | [1..11] months | - * | 1 ... N years | [1..N] years | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {'s'|'m'|'h'|'d'|'M'|'Y'} [options.unit] - if specified, will force a unit - * @param {'floor'|'ceil'|'round'} [options.partialMethod='floor'] - which way to round partial units - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWordsStrict( - * new Date(2014, 6, 2), - * new Date(2015, 0, 2) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * ) - * //=> '15 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> '1 year ago' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, in minutes? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {unit: 'm'} - * ) - * //=> '525600 minutes' - * - * @example - * // What is the distance from 1 January 2016 - * // to 28 January 2015, in months, rounded up? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 28), - * new Date(2015, 0, 1), - * {unit: 'M', partialMethod: 'ceil'} - * ) - * //=> '1 month' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsStrict( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> '1 jaro' - */ - function distanceInWordsStrict (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var unit; - var mathPartial = Math[options.partialMethod ? String(options.partialMethod) : 'floor']; - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = mathPartial(seconds / 60) - offset; - var hours, days, months, years; - - if (options.unit) { - unit = String(options.unit); - } else { - if (minutes < 1) { - unit = 's'; - } else if (minutes < 60) { - unit = 'm'; - } else if (minutes < MINUTES_IN_DAY) { - unit = 'h'; - } else if (minutes < MINUTES_IN_MONTH) { - unit = 'd'; - } else if (minutes < MINUTES_IN_YEAR) { - unit = 'M'; - } else { - unit = 'Y'; - } - } - - // 0 up to 60 seconds - if (unit === 's') { - return localize('xSeconds', seconds, localizeOptions) - - // 1 up to 60 mins - } else if (unit === 'm') { - return localize('xMinutes', minutes, localizeOptions) - - // 1 up to 24 hours - } else if (unit === 'h') { - hours = mathPartial(minutes / 60); - return localize('xHours', hours, localizeOptions) - - // 1 up to 30 days - } else if (unit === 'd') { - days = mathPartial(minutes / MINUTES_IN_DAY); - return localize('xDays', days, localizeOptions) - - // 1 up to 12 months - } else if (unit === 'M') { - months = mathPartial(minutes / MINUTES_IN_MONTH); - return localize('xMonths', months, localizeOptions) - - // 1 year up to max Date - } else if (unit === 'Y') { - years = mathPartial(minutes / MINUTES_IN_YEAR); - return localize('xYears', years, localizeOptions) - } - - throw new Error('Unknown unit: ' + unit) - } - - var distance_in_words_strict = distanceInWordsStrict; - - /** - * @category Common Helpers - * @summary Return the distance between the given date and now in words. - * - * @description - * Return the distance between the given date and now in words. - * - * | Distance to now | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance to now | Result | - * |---------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} date - the given date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result specifies if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // If today is 1 January 2015, what is the distance to 2 July 2014? - * var result = distanceInWordsToNow( - * new Date(2014, 6, 2) - * ) - * //=> '6 months' - * - * @example - * // If now is 1 January 2015 00:00:00, - * // what is the distance to 1 January 2015 00:00:15, including seconds? - * var result = distanceInWordsToNow( - * new Date(2015, 0, 1, 0, 0, 15), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 January 2016, with a suffix? - * var result = distanceInWordsToNow( - * new Date(2016, 0, 1), - * {addSuffix: true} - * ) - * //=> 'in about 1 year' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 August 2016 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsToNow( - * new Date(2016, 7, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ - function distanceInWordsToNow (dirtyDate, dirtyOptions) { - return distance_in_words(Date.now(), dirtyDate, dirtyOptions) - } - - var distance_in_words_to_now = distanceInWordsToNow; - - /** - * @category Day Helpers - * @summary Return the array of dates within the specified range. - * - * @description - * Return the array of dates within the specified range. - * - * @param {Date|String|Number} startDate - the first date - * @param {Date|String|Number} endDate - the last date - * @param {Number} [step=1] - the step between each day - * @returns {Date[]} the array with starts of days from the day of startDate to the day of endDate - * @throws {Error} startDate cannot be after endDate - * - * @example - * // Each day between 6 October 2014 and 10 October 2014: - * var result = eachDay( - * new Date(2014, 9, 6), - * new Date(2014, 9, 10) - * ) - * //=> [ - * // Mon Oct 06 2014 00:00:00, - * // Tue Oct 07 2014 00:00:00, - * // Wed Oct 08 2014 00:00:00, - * // Thu Oct 09 2014 00:00:00, - * // Fri Oct 10 2014 00:00:00 - * // ] - */ - function eachDay (dirtyStartDate, dirtyEndDate, dirtyStep) { - var startDate = parse_1(dirtyStartDate); - var endDate = parse_1(dirtyEndDate); - var step = dirtyStep !== undefined ? dirtyStep : 1; - - var endTime = endDate.getTime(); - - if (startDate.getTime() > endTime) { - throw new Error('The first date cannot be after the second date') - } - - var dates = []; - - var currentDate = startDate; - currentDate.setHours(0, 0, 0, 0); - - while (currentDate.getTime() <= endTime) { - dates.push(parse_1(currentDate)); - currentDate.setDate(currentDate.getDate() + step); - } - - return dates - } - - var each_day = eachDay; - - /** - * @category Day Helpers - * @summary Return the end of a day for the given date. - * - * @description - * Return the end of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a day - * - * @example - * // The end of a day for 2 September 2014 11:55:00: - * var result = endOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 23:59:59.999 - */ - function endOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_day = endOfDay; - - /** - * @category Hour Helpers - * @summary Return the end of an hour for the given date. - * - * @description - * Return the end of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an hour - * - * @example - * // The end of an hour for 2 September 2014 11:55:00: - * var result = endOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:59:59.999 - */ - function endOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(59, 59, 999); - return date - } - - var end_of_hour = endOfHour; - - /** - * @category Week Helpers - * @summary Return the end of a week for the given date. - * - * @description - * Return the end of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the end of a week - * - * @example - * // The end of a week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 23:59:59.999 - * - * @example - * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 23:59:59.999 - */ - function endOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setDate(date.getDate() + diff); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_week = endOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the end of an ISO week for the given date. - * - * @description - * Return the end of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week - * - * @example - * // The end of an ISO week for 2 September 2014 11:55:00: - * var result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 23:59:59.999 - */ - function endOfISOWeek (dirtyDate) { - return end_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var end_of_iso_week = endOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the end of an ISO week-numbering year for the given date. - * - * @description - * Return the end of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The end of an ISO week-numbering year for 2 July 2005: - * var result = endOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 23:59:59.999 - */ - function endOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuaryOfNextYear); - date.setMilliseconds(date.getMilliseconds() - 1); - return date - } - - var end_of_iso_year = endOfISOYear; - - /** - * @category Minute Helpers - * @summary Return the end of a minute for the given date. - * - * @description - * Return the end of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a minute - * - * @example - * // The end of a minute for 1 December 2014 22:15:45.400: - * var result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:59.999 - */ - function endOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(59, 999); - return date - } - - var end_of_minute = endOfMinute; - - /** - * @category Month Helpers - * @summary Return the end of a month for the given date. - * - * @description - * Return the end of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a month - * - * @example - * // The end of a month for 2 September 2014 11:55:00: - * var result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ - function endOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_month = endOfMonth; - - /** - * @category Quarter Helpers - * @summary Return the end of a year quarter for the given date. - * - * @description - * Return the end of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a quarter - * - * @example - * // The end of a quarter for 2 September 2014 11:55:00: - * var result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ - function endOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_quarter = endOfQuarter; - - /** - * @category Second Helpers - * @summary Return the end of a second for the given date. - * - * @description - * Return the end of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a second - * - * @example - * // The end of a second for 1 December 2014 22:15:45.400: - * var result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.999 - */ - function endOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(999); - return date - } - - var end_of_second = endOfSecond; - - /** - * @category Day Helpers - * @summary Return the end of today. - * - * @description - * Return the end of today. - * - * @returns {Date} the end of today - * - * @example - * // If today is 6 October 2014: - * var result = endOfToday() - * //=> Mon Oct 6 2014 23:59:59.999 - */ - function endOfToday () { - return end_of_day(new Date()) - } - - var end_of_today = endOfToday; - - /** - * @category Day Helpers - * @summary Return the end of tomorrow. - * - * @description - * Return the end of tomorrow. - * - * @returns {Date} the end of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = endOfTomorrow() - * //=> Tue Oct 7 2014 23:59:59.999 - */ - function endOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_tomorrow = endOfTomorrow; - - /** - * @category Year Helpers - * @summary Return the end of a year for the given date. - * - * @description - * Return the end of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a year - * - * @example - * // The end of a year for 2 September 2014 11:55:00: - * var result = endOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 23:59:59.999 - */ - function endOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_year = endOfYear; - - /** - * @category Day Helpers - * @summary Return the end of yesterday. - * - * @description - * Return the end of yesterday. - * - * @returns {Date} the end of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = endOfYesterday() - * //=> Sun Oct 5 2014 23:59:59.999 - */ - function endOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_yesterday = endOfYesterday; - - /** - * @category Year Helpers - * @summary Return the start of a year for the given date. - * - * @description - * Return the start of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a year - * - * @example - * // The start of a year for 2 September 2014 11:55:00: - * var result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Jan 01 2014 00:00:00 - */ - function startOfYear (dirtyDate) { - var cleanDate = parse_1(dirtyDate); - var date = new Date(0); - date.setFullYear(cleanDate.getFullYear(), 0, 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_year = startOfYear; - - /** - * @category Day Helpers - * @summary Get the day of the year of the given date. - * - * @description - * Get the day of the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of year - * - * @example - * // Which day of the year is 2 July 2014? - * var result = getDayOfYear(new Date(2014, 6, 2)) - * //=> 183 - */ - function getDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = difference_in_calendar_days(date, start_of_year(date)); - var dayOfYear = diff + 1; - return dayOfYear - } - - var get_day_of_year = getDayOfYear; - - var MILLISECONDS_IN_WEEK$1 = 604800000; - - /** - * @category ISO Week Helpers - * @summary Get the ISO week of the given date. - * - * @description - * Get the ISO week of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week - * - * @example - * // Which week of the ISO-week numbering year is 2 January 2005? - * var result = getISOWeek(new Date(2005, 0, 2)) - * //=> 53 - */ - function getISOWeek (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = start_of_iso_week(date).getTime() - start_of_iso_year(date).getTime(); - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1 - } - - var get_iso_week = getISOWeek; - - /** - * @category Common Helpers - * @summary Is the given date valid? - * - * @description - * Returns false if argument is Invalid Date and true otherwise. - * Invalid Date is a Date, whose time value is NaN. - * - * Time value of Date: http://es5.github.io/#x15.9.1.1 - * - * @param {Date} date - the date to check - * @returns {Boolean} the date is valid - * @throws {TypeError} argument must be an instance of Date - * - * @example - * // For the valid date: - * var result = isValid(new Date(2014, 1, 31)) - * //=> true - * - * @example - * // For the invalid date: - * var result = isValid(new Date('')) - * //=> false - */ - function isValid (dirtyDate) { - if (is_date(dirtyDate)) { - return !isNaN(dirtyDate) - } else { - throw new TypeError(toString.call(dirtyDate) + ' is not an instance of Date') - } - } - - var is_valid = isValid; - - /** - * @category Common Helpers - * @summary Format the date. - * - * @description - * Return the formatted date string in the given format. - * - * Accepted tokens: - * | Unit | Token | Result examples | - * |-------------------------|-------|----------------------------------| - * | Month | M | 1, 2, ..., 12 | - * | | Mo | 1st, 2nd, ..., 12th | - * | | MM | 01, 02, ..., 12 | - * | | MMM | Jan, Feb, ..., Dec | - * | | MMMM | January, February, ..., December | - * | Quarter | Q | 1, 2, 3, 4 | - * | | Qo | 1st, 2nd, 3rd, 4th | - * | Day of month | D | 1, 2, ..., 31 | - * | | Do | 1st, 2nd, ..., 31st | - * | | DD | 01, 02, ..., 31 | - * | Day of year | DDD | 1, 2, ..., 366 | - * | | DDDo | 1st, 2nd, ..., 366th | - * | | DDDD | 001, 002, ..., 366 | - * | Day of week | d | 0, 1, ..., 6 | - * | | do | 0th, 1st, ..., 6th | - * | | dd | Su, Mo, ..., Sa | - * | | ddd | Sun, Mon, ..., Sat | - * | | dddd | Sunday, Monday, ..., Saturday | - * | Day of ISO week | E | 1, 2, ..., 7 | - * | ISO week | W | 1, 2, ..., 53 | - * | | Wo | 1st, 2nd, ..., 53rd | - * | | WW | 01, 02, ..., 53 | - * | Year | YY | 00, 01, ..., 99 | - * | | YYYY | 1900, 1901, ..., 2099 | - * | ISO week-numbering year | GG | 00, 01, ..., 99 | - * | | GGGG | 1900, 1901, ..., 2099 | - * | AM/PM | A | AM, PM | - * | | a | am, pm | - * | | aa | a.m., p.m. | - * | Hour | H | 0, 1, ... 23 | - * | | HH | 00, 01, ... 23 | - * | | h | 1, 2, ..., 12 | - * | | hh | 01, 02, ..., 12 | - * | Minute | m | 0, 1, ..., 59 | - * | | mm | 00, 01, ..., 59 | - * | Second | s | 0, 1, ..., 59 | - * | | ss | 00, 01, ..., 59 | - * | 1/10 of second | S | 0, 1, ..., 9 | - * | 1/100 of second | SS | 00, 01, ..., 99 | - * | Millisecond | SSS | 000, 001, ..., 999 | - * | Timezone | Z | -01:00, +00:00, ... +12:00 | - * | | ZZ | -0100, +0000, ..., +1200 | - * | Seconds timestamp | X | 512969520 | - * | Milliseconds timestamp | x | 512969520900 | - * - * The characters wrapped in square brackets are escaped. - * - * The result may vary by locale. - * - * @param {Date|String|Number} date - the original date - * @param {String} [format='YYYY-MM-DDTHH:mm:ss.SSSZ'] - the string of tokens - * @param {Object} [options] - the object with options - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the formatted date string - * - * @example - * // Represent 11 February 2014 in middle-endian format: - * var result = format( - * new Date(2014, 1, 11), - * 'MM/DD/YYYY' - * ) - * //=> '02/11/2014' - * - * @example - * // Represent 2 July 2014 in Esperanto: - * var eoLocale = require('date-fns/locale/eo') - * var result = format( - * new Date(2014, 6, 2), - * 'Do [de] MMMM YYYY', - * {locale: eoLocale} - * ) - * //=> '2-a de julio 2014' - */ - function format (dirtyDate, dirtyFormatStr, dirtyOptions) { - var formatStr = dirtyFormatStr ? String(dirtyFormatStr) : 'YYYY-MM-DDTHH:mm:ss.SSSZ'; - var options = dirtyOptions || {}; - - var locale = options.locale; - var localeFormatters = en.format.formatters; - var formattingTokensRegExp = en.format.formattingTokensRegExp; - if (locale && locale.format && locale.format.formatters) { - localeFormatters = locale.format.formatters; - - if (locale.format.formattingTokensRegExp) { - formattingTokensRegExp = locale.format.formattingTokensRegExp; - } - } - - var date = parse_1(dirtyDate); - - if (!is_valid(date)) { - return 'Invalid Date' - } - - var formatFn = buildFormatFn(formatStr, localeFormatters, formattingTokensRegExp); - - return formatFn(date) - } - - var formatters = { - // Month: 1, 2, ..., 12 - 'M': function (date) { - return date.getMonth() + 1 - }, - - // Month: 01, 02, ..., 12 - 'MM': function (date) { - return addLeadingZeros(date.getMonth() + 1, 2) - }, - - // Quarter: 1, 2, 3, 4 - 'Q': function (date) { - return Math.ceil((date.getMonth() + 1) / 3) - }, - - // Day of month: 1, 2, ..., 31 - 'D': function (date) { - return date.getDate() - }, - - // Day of month: 01, 02, ..., 31 - 'DD': function (date) { - return addLeadingZeros(date.getDate(), 2) - }, - - // Day of year: 1, 2, ..., 366 - 'DDD': function (date) { - return get_day_of_year(date) - }, - - // Day of year: 001, 002, ..., 366 - 'DDDD': function (date) { - return addLeadingZeros(get_day_of_year(date), 3) - }, - - // Day of week: 0, 1, ..., 6 - 'd': function (date) { - return date.getDay() - }, - - // Day of ISO week: 1, 2, ..., 7 - 'E': function (date) { - return date.getDay() || 7 - }, - - // ISO week: 1, 2, ..., 53 - 'W': function (date) { - return get_iso_week(date) - }, - - // ISO week: 01, 02, ..., 53 - 'WW': function (date) { - return addLeadingZeros(get_iso_week(date), 2) - }, - - // Year: 00, 01, ..., 99 - 'YY': function (date) { - return addLeadingZeros(date.getFullYear(), 4).substr(2) - }, - - // Year: 1900, 1901, ..., 2099 - 'YYYY': function (date) { - return addLeadingZeros(date.getFullYear(), 4) - }, - - // ISO week-numbering year: 00, 01, ..., 99 - 'GG': function (date) { - return String(get_iso_year(date)).substr(2) - }, - - // ISO week-numbering year: 1900, 1901, ..., 2099 - 'GGGG': function (date) { - return get_iso_year(date) - }, - - // Hour: 0, 1, ... 23 - 'H': function (date) { - return date.getHours() - }, - - // Hour: 00, 01, ..., 23 - 'HH': function (date) { - return addLeadingZeros(date.getHours(), 2) - }, - - // Hour: 1, 2, ..., 12 - 'h': function (date) { - var hours = date.getHours(); - if (hours === 0) { - return 12 - } else if (hours > 12) { - return hours % 12 - } else { - return hours - } - }, - - // Hour: 01, 02, ..., 12 - 'hh': function (date) { - return addLeadingZeros(formatters['h'](date), 2) - }, - - // Minute: 0, 1, ..., 59 - 'm': function (date) { - return date.getMinutes() - }, - - // Minute: 00, 01, ..., 59 - 'mm': function (date) { - return addLeadingZeros(date.getMinutes(), 2) - }, - - // Second: 0, 1, ..., 59 - 's': function (date) { - return date.getSeconds() - }, - - // Second: 00, 01, ..., 59 - 'ss': function (date) { - return addLeadingZeros(date.getSeconds(), 2) - }, - - // 1/10 of second: 0, 1, ..., 9 - 'S': function (date) { - return Math.floor(date.getMilliseconds() / 100) - }, - - // 1/100 of second: 00, 01, ..., 99 - 'SS': function (date) { - return addLeadingZeros(Math.floor(date.getMilliseconds() / 10), 2) - }, - - // Millisecond: 000, 001, ..., 999 - 'SSS': function (date) { - return addLeadingZeros(date.getMilliseconds(), 3) - }, - - // Timezone: -01:00, +00:00, ... +12:00 - 'Z': function (date) { - return formatTimezone(date.getTimezoneOffset(), ':') - }, - - // Timezone: -0100, +0000, ... +1200 - 'ZZ': function (date) { - return formatTimezone(date.getTimezoneOffset()) - }, - - // Seconds timestamp: 512969520 - 'X': function (date) { - return Math.floor(date.getTime() / 1000) - }, - - // Milliseconds timestamp: 512969520900 - 'x': function (date) { - return date.getTime() - } - }; - - function buildFormatFn (formatStr, localeFormatters, formattingTokensRegExp) { - var array = formatStr.match(formattingTokensRegExp); - var length = array.length; - - var i; - var formatter; - for (i = 0; i < length; i++) { - formatter = localeFormatters[array[i]] || formatters[array[i]]; - if (formatter) { - array[i] = formatter; - } else { - array[i] = removeFormattingTokens(array[i]); - } - } - - return function (date) { - var output = ''; - for (var i = 0; i < length; i++) { - if (array[i] instanceof Function) { - output += array[i](date, formatters); - } else { - output += array[i]; - } - } - return output - } - } - - function removeFormattingTokens (input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|]$/g, '') - } - return input.replace(/\\/g, '') - } - - function formatTimezone (offset, delimeter) { - delimeter = delimeter || ''; - var sign = offset > 0 ? '-' : '+'; - var absOffset = Math.abs(offset); - var hours = Math.floor(absOffset / 60); - var minutes = absOffset % 60; - return sign + addLeadingZeros(hours, 2) + delimeter + addLeadingZeros(minutes, 2) - } - - function addLeadingZeros (number, targetLength) { - var output = Math.abs(number).toString(); - while (output.length < targetLength) { - output = '0' + output; - } - return output - } - - var format_1 = format; - - /** - * @category Day Helpers - * @summary Get the day of the month of the given date. - * - * @description - * Get the day of the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of month - * - * @example - * // Which day of the month is 29 February 2012? - * var result = getDate(new Date(2012, 1, 29)) - * //=> 29 - */ - function getDate (dirtyDate) { - var date = parse_1(dirtyDate); - var dayOfMonth = date.getDate(); - return dayOfMonth - } - - var get_date = getDate; - - /** - * @category Weekday Helpers - * @summary Get the day of the week of the given date. - * - * @description - * Get the day of the week of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of week - * - * @example - * // Which day of the week is 29 February 2012? - * var result = getDay(new Date(2012, 1, 29)) - * //=> 3 - */ - function getDay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day - } - - var get_day = getDay; - - /** - * @category Year Helpers - * @summary Is the given date in the leap year? - * - * @description - * Is the given date in the leap year? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the leap year - * - * @example - * // Is 1 September 2012 in the leap year? - * var result = isLeapYear(new Date(2012, 8, 1)) - * //=> true - */ - function isLeapYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0 - } - - var is_leap_year = isLeapYear; - - /** - * @category Year Helpers - * @summary Get the number of days in a year of the given date. - * - * @description - * Get the number of days in a year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a year - * - * @example - * // How many days are in 2012? - * var result = getDaysInYear(new Date(2012, 0, 1)) - * //=> 366 - */ - function getDaysInYear (dirtyDate) { - return is_leap_year(dirtyDate) ? 366 : 365 - } - - var get_days_in_year = getDaysInYear; - - /** - * @category Hour Helpers - * @summary Get the hours of the given date. - * - * @description - * Get the hours of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the hours - * - * @example - * // Get the hours of 29 February 2012 11:45:00: - * var result = getHours(new Date(2012, 1, 29, 11, 45)) - * //=> 11 - */ - function getHours (dirtyDate) { - var date = parse_1(dirtyDate); - var hours = date.getHours(); - return hours - } - - var get_hours = getHours; - - /** - * @category Weekday Helpers - * @summary Get the day of the ISO week of the given date. - * - * @description - * Get the day of the ISO week of the given date, - * which is 7 for Sunday, 1 for Monday etc. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of ISO week - * - * @example - * // Which day of the ISO week is 26 February 2012? - * var result = getISODay(new Date(2012, 1, 26)) - * //=> 7 - */ - function getISODay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - - if (day === 0) { - day = 7; - } - - return day - } - - var get_iso_day = getISODay; - - var MILLISECONDS_IN_WEEK = 604800000; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of weeks in an ISO week-numbering year of the given date. - * - * @description - * Get the number of weeks in an ISO week-numbering year of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of ISO weeks in a year - * - * @example - * // How many weeks are in ISO week-numbering year 2015? - * var result = getISOWeeksInYear(new Date(2015, 1, 11)) - * //=> 53 - */ - function getISOWeeksInYear (dirtyDate) { - var thisYear = start_of_iso_year(dirtyDate); - var nextYear = start_of_iso_year(add_weeks(thisYear, 60)); - var diff = nextYear.valueOf() - thisYear.valueOf(); - // Round the number of weeks to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK) - } - - var get_iso_weeks_in_year = getISOWeeksInYear; - - /** - * @category Millisecond Helpers - * @summary Get the milliseconds of the given date. - * - * @description - * Get the milliseconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the milliseconds - * - * @example - * // Get the milliseconds of 29 February 2012 11:45:05.123: - * var result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 123 - */ - function getMilliseconds (dirtyDate) { - var date = parse_1(dirtyDate); - var milliseconds = date.getMilliseconds(); - return milliseconds - } - - var get_milliseconds = getMilliseconds; - - /** - * @category Minute Helpers - * @summary Get the minutes of the given date. - * - * @description - * Get the minutes of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the minutes - * - * @example - * // Get the minutes of 29 February 2012 11:45:05: - * var result = getMinutes(new Date(2012, 1, 29, 11, 45, 5)) - * //=> 45 - */ - function getMinutes (dirtyDate) { - var date = parse_1(dirtyDate); - var minutes = date.getMinutes(); - return minutes - } - - var get_minutes = getMinutes; - - /** - * @category Month Helpers - * @summary Get the month of the given date. - * - * @description - * Get the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the month - * - * @example - * // Which month is 29 February 2012? - * var result = getMonth(new Date(2012, 1, 29)) - * //=> 1 - */ - function getMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - return month - } - - var get_month = getMonth; - - var MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000; - - /** - * @category Range Helpers - * @summary Get the number of days that overlap in two date ranges - * - * @description - * Get the number of days that overlap in two date ranges - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Number} the number of days that overlap in two date ranges - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges adds 1 for each started overlapping day: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> 3 - * - * @example - * // For non-overlapping date ranges returns 0: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> 0 - */ - function getOverlappingDaysInRanges (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - var isOverlapping = initialStartTime < comparedEndTime && comparedStartTime < initialEndTime; - - if (!isOverlapping) { - return 0 - } - - var overlapStartDate = comparedStartTime < initialStartTime - ? initialStartTime - : comparedStartTime; - - var overlapEndDate = comparedEndTime > initialEndTime - ? initialEndTime - : comparedEndTime; - - var differenceInMs = overlapEndDate - overlapStartDate; - - return Math.ceil(differenceInMs / MILLISECONDS_IN_DAY) - } - - var get_overlapping_days_in_ranges = getOverlappingDaysInRanges; - - /** - * @category Second Helpers - * @summary Get the seconds of the given date. - * - * @description - * Get the seconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the seconds - * - * @example - * // Get the seconds of 29 February 2012 11:45:05.123: - * var result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 5 - */ - function getSeconds (dirtyDate) { - var date = parse_1(dirtyDate); - var seconds = date.getSeconds(); - return seconds - } - - var get_seconds = getSeconds; - - /** - * @category Timestamp Helpers - * @summary Get the milliseconds timestamp of the given date. - * - * @description - * Get the milliseconds timestamp of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the timestamp - * - * @example - * // Get the timestamp of 29 February 2012 11:45:05.123: - * var result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 1330515905123 - */ - function getTime (dirtyDate) { - var date = parse_1(dirtyDate); - var timestamp = date.getTime(); - return timestamp - } - - var get_time = getTime; - - /** - * @category Year Helpers - * @summary Get the year of the given date. - * - * @description - * Get the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the year - * - * @example - * // Which year is 2 July 2014? - * var result = getYear(new Date(2014, 6, 2)) - * //=> 2014 - */ - function getYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year - } - - var get_year = getYear; - - /** - * @category Common Helpers - * @summary Is the first date after the second one? - * - * @description - * Is the first date after the second one? - * - * @param {Date|String|Number} date - the date that should be after the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is after the second date - * - * @example - * // Is 10 July 1989 after 11 February 1987? - * var result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> true - */ - function isAfter (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() > dateToCompare.getTime() - } - - var is_after = isAfter; - - /** - * @category Common Helpers - * @summary Is the first date before the second one? - * - * @description - * Is the first date before the second one? - * - * @param {Date|String|Number} date - the date that should be before the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is before the second date - * - * @example - * // Is 10 July 1989 before 11 February 1987? - * var result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> false - */ - function isBefore (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() < dateToCompare.getTime() - } - - var is_before = isBefore; - - /** - * @category Common Helpers - * @summary Are the given dates equal? - * - * @description - * Are the given dates equal? - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Boolean} the dates are equal - * - * @example - * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal? - * var result = isEqual( - * new Date(2014, 6, 2, 6, 30, 45, 0) - * new Date(2014, 6, 2, 6, 30, 45, 500) - * ) - * //=> false - */ - function isEqual (dirtyLeftDate, dirtyRightDate) { - var dateLeft = parse_1(dirtyLeftDate); - var dateRight = parse_1(dirtyRightDate); - return dateLeft.getTime() === dateRight.getTime() - } - - var is_equal = isEqual; - - /** - * @category Month Helpers - * @summary Is the given date the first day of a month? - * - * @description - * Is the given date the first day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the first day of a month - * - * @example - * // Is 1 September 2014 the first day of a month? - * var result = isFirstDayOfMonth(new Date(2014, 8, 1)) - * //=> true - */ - function isFirstDayOfMonth (dirtyDate) { - return parse_1(dirtyDate).getDate() === 1 - } - - var is_first_day_of_month = isFirstDayOfMonth; - - /** - * @category Weekday Helpers - * @summary Is the given date Friday? - * - * @description - * Is the given date Friday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Friday - * - * @example - * // Is 26 September 2014 Friday? - * var result = isFriday(new Date(2014, 8, 26)) - * //=> true - */ - function isFriday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 5 - } - - var is_friday = isFriday; - - /** - * @category Common Helpers - * @summary Is the given date in the future? - * - * @description - * Is the given date in the future? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the future - * - * @example - * // If today is 6 October 2014, is 31 December 2014 in the future? - * var result = isFuture(new Date(2014, 11, 31)) - * //=> true - */ - function isFuture (dirtyDate) { - return parse_1(dirtyDate).getTime() > new Date().getTime() - } - - var is_future = isFuture; - - /** - * @category Month Helpers - * @summary Is the given date the last day of a month? - * - * @description - * Is the given date the last day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the last day of a month - * - * @example - * // Is 28 February 2014 the last day of a month? - * var result = isLastDayOfMonth(new Date(2014, 1, 28)) - * //=> true - */ - function isLastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - return end_of_day(date).getTime() === end_of_month(date).getTime() - } - - var is_last_day_of_month = isLastDayOfMonth; - - /** - * @category Weekday Helpers - * @summary Is the given date Monday? - * - * @description - * Is the given date Monday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Monday - * - * @example - * // Is 22 September 2014 Monday? - * var result = isMonday(new Date(2014, 8, 22)) - * //=> true - */ - function isMonday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 1 - } - - var is_monday = isMonday; - - /** - * @category Common Helpers - * @summary Is the given date in the past? - * - * @description - * Is the given date in the past? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the past - * - * @example - * // If today is 6 October 2014, is 2 July 2014 in the past? - * var result = isPast(new Date(2014, 6, 2)) - * //=> true - */ - function isPast (dirtyDate) { - return parse_1(dirtyDate).getTime() < new Date().getTime() - } - - var is_past = isPast; - - /** - * @category Day Helpers - * @summary Are the given dates in the same day? - * - * @description - * Are the given dates in the same day? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same day - * - * @example - * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? - * var result = isSameDay( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 18, 0) - * ) - * //=> true - */ - function isSameDay (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfDay = start_of_day(dirtyDateLeft); - var dateRightStartOfDay = start_of_day(dirtyDateRight); - - return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime() - } - - var is_same_day = isSameDay; - - /** - * @category Hour Helpers - * @summary Return the start of an hour for the given date. - * - * @description - * Return the start of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an hour - * - * @example - * // The start of an hour for 2 September 2014 11:55:00: - * var result = startOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:00:00 - */ - function startOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(0, 0, 0); - return date - } - - var start_of_hour = startOfHour; - - /** - * @category Hour Helpers - * @summary Are the given dates in the same hour? - * - * @description - * Are the given dates in the same hour? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same hour - * - * @example - * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour? - * var result = isSameHour( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 6, 30) - * ) - * //=> true - */ - function isSameHour (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfHour = start_of_hour(dirtyDateLeft); - var dateRightStartOfHour = start_of_hour(dirtyDateRight); - - return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime() - } - - var is_same_hour = isSameHour; - - /** - * @category Week Helpers - * @summary Are the given dates in the same week? - * - * @description - * Are the given dates in the same week? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the dates are in the same week - * - * @example - * // Are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4) - * ) - * //=> true - * - * @example - * // If week starts with Monday, - * // are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4), - * {weekStartsOn: 1} - * ) - * //=> false - */ - function isSameWeek (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var dateLeftStartOfWeek = start_of_week(dirtyDateLeft, dirtyOptions); - var dateRightStartOfWeek = start_of_week(dirtyDateRight, dirtyOptions); - - return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime() - } - - var is_same_week = isSameWeek; - - /** - * @category ISO Week Helpers - * @summary Are the given dates in the same ISO week? - * - * @description - * Are the given dates in the same ISO week? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week - * - * @example - * // Are 1 September 2014 and 7 September 2014 in the same ISO week? - * var result = isSameISOWeek( - * new Date(2014, 8, 1), - * new Date(2014, 8, 7) - * ) - * //=> true - */ - function isSameISOWeek (dirtyDateLeft, dirtyDateRight) { - return is_same_week(dirtyDateLeft, dirtyDateRight, {weekStartsOn: 1}) - } - - var is_same_iso_week = isSameISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Are the given dates in the same ISO week-numbering year? - * - * @description - * Are the given dates in the same ISO week-numbering year? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week-numbering year - * - * @example - * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? - * var result = isSameISOYear( - * new Date(2003, 11, 29), - * new Date(2005, 0, 2) - * ) - * //=> true - */ - function isSameISOYear (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfYear = start_of_iso_year(dirtyDateLeft); - var dateRightStartOfYear = start_of_iso_year(dirtyDateRight); - - return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime() - } - - var is_same_iso_year = isSameISOYear; - - /** - * @category Minute Helpers - * @summary Return the start of a minute for the given date. - * - * @description - * Return the start of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a minute - * - * @example - * // The start of a minute for 1 December 2014 22:15:45.400: - * var result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:00 - */ - function startOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(0, 0); - return date - } - - var start_of_minute = startOfMinute; - - /** - * @category Minute Helpers - * @summary Are the given dates in the same minute? - * - * @description - * Are the given dates in the same minute? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same minute - * - * @example - * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 - * // in the same minute? - * var result = isSameMinute( - * new Date(2014, 8, 4, 6, 30), - * new Date(2014, 8, 4, 6, 30, 15) - * ) - * //=> true - */ - function isSameMinute (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfMinute = start_of_minute(dirtyDateLeft); - var dateRightStartOfMinute = start_of_minute(dirtyDateRight); - - return dateLeftStartOfMinute.getTime() === dateRightStartOfMinute.getTime() - } - - var is_same_minute = isSameMinute; - - /** - * @category Month Helpers - * @summary Are the given dates in the same month? - * - * @description - * Are the given dates in the same month? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same month - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same month? - * var result = isSameMonth( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ - function isSameMonth (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() && - dateLeft.getMonth() === dateRight.getMonth() - } - - var is_same_month = isSameMonth; - - /** - * @category Quarter Helpers - * @summary Return the start of a year quarter for the given date. - * - * @description - * Return the start of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a quarter - * - * @example - * // The start of a quarter for 2 September 2014 11:55:00: - * var result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Jul 01 2014 00:00:00 - */ - function startOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3; - date.setMonth(month, 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_quarter = startOfQuarter; - - /** - * @category Quarter Helpers - * @summary Are the given dates in the same year quarter? - * - * @description - * Are the given dates in the same year quarter? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same quarter - * - * @example - * // Are 1 January 2014 and 8 March 2014 in the same quarter? - * var result = isSameQuarter( - * new Date(2014, 0, 1), - * new Date(2014, 2, 8) - * ) - * //=> true - */ - function isSameQuarter (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfQuarter = start_of_quarter(dirtyDateLeft); - var dateRightStartOfQuarter = start_of_quarter(dirtyDateRight); - - return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime() - } - - var is_same_quarter = isSameQuarter; - - /** - * @category Second Helpers - * @summary Return the start of a second for the given date. - * - * @description - * Return the start of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a second - * - * @example - * // The start of a second for 1 December 2014 22:15:45.400: - * var result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.000 - */ - function startOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(0); - return date - } - - var start_of_second = startOfSecond; - - /** - * @category Second Helpers - * @summary Are the given dates in the same second? - * - * @description - * Are the given dates in the same second? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same second - * - * @example - * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 - * // in the same second? - * var result = isSameSecond( - * new Date(2014, 8, 4, 6, 30, 15), - * new Date(2014, 8, 4, 6, 30, 15, 500) - * ) - * //=> true - */ - function isSameSecond (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfSecond = start_of_second(dirtyDateLeft); - var dateRightStartOfSecond = start_of_second(dirtyDateRight); - - return dateLeftStartOfSecond.getTime() === dateRightStartOfSecond.getTime() - } - - var is_same_second = isSameSecond; - - /** - * @category Year Helpers - * @summary Are the given dates in the same year? - * - * @description - * Are the given dates in the same year? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same year - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same year? - * var result = isSameYear( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ - function isSameYear (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() - } - - var is_same_year = isSameYear; - - /** - * @category Weekday Helpers - * @summary Is the given date Saturday? - * - * @description - * Is the given date Saturday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Saturday - * - * @example - * // Is 27 September 2014 Saturday? - * var result = isSaturday(new Date(2014, 8, 27)) - * //=> true - */ - function isSaturday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 6 - } - - var is_saturday = isSaturday; - - /** - * @category Weekday Helpers - * @summary Is the given date Sunday? - * - * @description - * Is the given date Sunday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Sunday - * - * @example - * // Is 21 September 2014 Sunday? - * var result = isSunday(new Date(2014, 8, 21)) - * //=> true - */ - function isSunday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 0 - } - - var is_sunday = isSunday; - - /** - * @category Hour Helpers - * @summary Is the given date in the same hour as the current date? - * - * @description - * Is the given date in the same hour as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this hour - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:00:00 in this hour? - * var result = isThisHour(new Date(2014, 8, 25, 18)) - * //=> true - */ - function isThisHour (dirtyDate) { - return is_same_hour(new Date(), dirtyDate) - } - - var is_this_hour = isThisHour; - - /** - * @category ISO Week Helpers - * @summary Is the given date in the same ISO week as the current date? - * - * @description - * Is the given date in the same ISO week as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week - * - * @example - * // If today is 25 September 2014, is 22 September 2014 in this ISO week? - * var result = isThisISOWeek(new Date(2014, 8, 22)) - * //=> true - */ - function isThisISOWeek (dirtyDate) { - return is_same_iso_week(new Date(), dirtyDate) - } - - var is_this_iso_week = isThisISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Is the given date in the same ISO week-numbering year as the current date? - * - * @description - * Is the given date in the same ISO week-numbering year as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week-numbering year - * - * @example - * // If today is 25 September 2014, - * // is 30 December 2013 in this ISO week-numbering year? - * var result = isThisISOYear(new Date(2013, 11, 30)) - * //=> true - */ - function isThisISOYear (dirtyDate) { - return is_same_iso_year(new Date(), dirtyDate) - } - - var is_this_iso_year = isThisISOYear; - - /** - * @category Minute Helpers - * @summary Is the given date in the same minute as the current date? - * - * @description - * Is the given date in the same minute as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this minute - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:00 in this minute? - * var result = isThisMinute(new Date(2014, 8, 25, 18, 30)) - * //=> true - */ - function isThisMinute (dirtyDate) { - return is_same_minute(new Date(), dirtyDate) - } - - var is_this_minute = isThisMinute; - - /** - * @category Month Helpers - * @summary Is the given date in the same month as the current date? - * - * @description - * Is the given date in the same month as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this month - * - * @example - * // If today is 25 September 2014, is 15 September 2014 in this month? - * var result = isThisMonth(new Date(2014, 8, 15)) - * //=> true - */ - function isThisMonth (dirtyDate) { - return is_same_month(new Date(), dirtyDate) - } - - var is_this_month = isThisMonth; - - /** - * @category Quarter Helpers - * @summary Is the given date in the same quarter as the current date? - * - * @description - * Is the given date in the same quarter as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this quarter - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this quarter? - * var result = isThisQuarter(new Date(2014, 6, 2)) - * //=> true - */ - function isThisQuarter (dirtyDate) { - return is_same_quarter(new Date(), dirtyDate) - } - - var is_this_quarter = isThisQuarter; - - /** - * @category Second Helpers - * @summary Is the given date in the same second as the current date? - * - * @description - * Is the given date in the same second as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this second - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:15.000 in this second? - * var result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15)) - * //=> true - */ - function isThisSecond (dirtyDate) { - return is_same_second(new Date(), dirtyDate) - } - - var is_this_second = isThisSecond; - - /** - * @category Week Helpers - * @summary Is the given date in the same week as the current date? - * - * @description - * Is the given date in the same week as the current date? - * - * @param {Date|String|Number} date - the date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the date is in this week - * - * @example - * // If today is 25 September 2014, is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21)) - * //=> true - * - * @example - * // If today is 25 September 2014 and week starts with Monday - * // is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21), {weekStartsOn: 1}) - * //=> false - */ - function isThisWeek (dirtyDate, dirtyOptions) { - return is_same_week(new Date(), dirtyDate, dirtyOptions) - } - - var is_this_week = isThisWeek; - - /** - * @category Year Helpers - * @summary Is the given date in the same year as the current date? - * - * @description - * Is the given date in the same year as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this year - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this year? - * var result = isThisYear(new Date(2014, 6, 2)) - * //=> true - */ - function isThisYear (dirtyDate) { - return is_same_year(new Date(), dirtyDate) - } - - var is_this_year = isThisYear; - - /** - * @category Weekday Helpers - * @summary Is the given date Thursday? - * - * @description - * Is the given date Thursday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Thursday - * - * @example - * // Is 25 September 2014 Thursday? - * var result = isThursday(new Date(2014, 8, 25)) - * //=> true - */ - function isThursday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 4 - } - - var is_thursday = isThursday; - - /** - * @category Day Helpers - * @summary Is the given date today? - * - * @description - * Is the given date today? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is today - * - * @example - * // If today is 6 October 2014, is 6 October 14:00:00 today? - * var result = isToday(new Date(2014, 9, 6, 14, 0)) - * //=> true - */ - function isToday (dirtyDate) { - return start_of_day(dirtyDate).getTime() === start_of_day(new Date()).getTime() - } - - var is_today = isToday; - - /** - * @category Day Helpers - * @summary Is the given date tomorrow? - * - * @description - * Is the given date tomorrow? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is tomorrow - * - * @example - * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow? - * var result = isTomorrow(new Date(2014, 9, 7, 14, 0)) - * //=> true - */ - function isTomorrow (dirtyDate) { - var tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 1); - return start_of_day(dirtyDate).getTime() === start_of_day(tomorrow).getTime() - } - - var is_tomorrow = isTomorrow; - - /** - * @category Weekday Helpers - * @summary Is the given date Tuesday? - * - * @description - * Is the given date Tuesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Tuesday - * - * @example - * // Is 23 September 2014 Tuesday? - * var result = isTuesday(new Date(2014, 8, 23)) - * //=> true - */ - function isTuesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 2 - } - - var is_tuesday = isTuesday; - - /** - * @category Weekday Helpers - * @summary Is the given date Wednesday? - * - * @description - * Is the given date Wednesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Wednesday - * - * @example - * // Is 24 September 2014 Wednesday? - * var result = isWednesday(new Date(2014, 8, 24)) - * //=> true - */ - function isWednesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 3 - } - - var is_wednesday = isWednesday; - - /** - * @category Weekday Helpers - * @summary Does the given date fall on a weekend? - * - * @description - * Does the given date fall on a weekend? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date falls on a weekend - * - * @example - * // Does 5 October 2014 fall on a weekend? - * var result = isWeekend(new Date(2014, 9, 5)) - * //=> true - */ - function isWeekend (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day === 0 || day === 6 - } - - var is_weekend = isWeekend; - - /** - * @category Range Helpers - * @summary Is the given date within the range? - * - * @description - * Is the given date within the range? - * - * @param {Date|String|Number} date - the date to check - * @param {Date|String|Number} startDate - the start of range - * @param {Date|String|Number} endDate - the end of range - * @returns {Boolean} the date is within the range - * @throws {Error} startDate cannot be after endDate - * - * @example - * // For the date within the range: - * isWithinRange( - * new Date(2014, 0, 3), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> true - * - * @example - * // For the date outside of the range: - * isWithinRange( - * new Date(2014, 0, 10), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> false - */ - function isWithinRange (dirtyDate, dirtyStartDate, dirtyEndDate) { - var time = parse_1(dirtyDate).getTime(); - var startTime = parse_1(dirtyStartDate).getTime(); - var endTime = parse_1(dirtyEndDate).getTime(); - - if (startTime > endTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return time >= startTime && time <= endTime - } - - var is_within_range = isWithinRange; - - /** - * @category Day Helpers - * @summary Is the given date yesterday? - * - * @description - * Is the given date yesterday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is yesterday - * - * @example - * // If today is 6 October 2014, is 5 October 14:00:00 yesterday? - * var result = isYesterday(new Date(2014, 9, 5, 14, 0)) - * //=> true - */ - function isYesterday (dirtyDate) { - var yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - return start_of_day(dirtyDate).getTime() === start_of_day(yesterday).getTime() - } - - var is_yesterday = isYesterday; - - /** - * @category Week Helpers - * @summary Return the last day of a week for the given date. - * - * @description - * Return the last day of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the last day of a week - * - * @example - * // The last day of a week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ - function lastDayOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setHours(0, 0, 0, 0); - date.setDate(date.getDate() + diff); - return date - } - - var last_day_of_week = lastDayOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the last day of an ISO week for the given date. - * - * @description - * Return the last day of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of an ISO week - * - * @example - * // The last day of an ISO week for 2 September 2014 11:55:00: - * var result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 00:00:00 - */ - function lastDayOfISOWeek (dirtyDate) { - return last_day_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var last_day_of_iso_week = lastDayOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the last day of an ISO week-numbering year for the given date. - * - * @description - * Return the last day of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The last day of an ISO week-numbering year for 2 July 2005: - * var result = lastDayOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 00:00:00 - */ - function lastDayOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year + 1, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - date.setDate(date.getDate() - 1); - return date - } - - var last_day_of_iso_year = lastDayOfISOYear; - - /** - * @category Month Helpers - * @summary Return the last day of a month for the given date. - * - * @description - * Return the last day of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a month - * - * @example - * // The last day of a month for 2 September 2014 11:55:00: - * var result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ - function lastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_month = lastDayOfMonth; - - /** - * @category Quarter Helpers - * @summary Return the last day of a year quarter for the given date. - * - * @description - * Return the last day of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a quarter - * - * @example - * // The last day of a quarter for 2 September 2014 11:55:00: - * var result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ - function lastDayOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_quarter = lastDayOfQuarter; - - /** - * @category Year Helpers - * @summary Return the last day of a year for the given date. - * - * @description - * Return the last day of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a year - * - * @example - * // The last day of a year for 2 September 2014 11:55:00: - * var result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 00:00:00 - */ - function lastDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_year = lastDayOfYear; - - /** - * @category Common Helpers - * @summary Return the latest of the given dates. - * - * @description - * Return the latest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the latest of the dates - * - * @example - * // Which of these dates is the latest? - * var result = max( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Sun Jul 02 1995 00:00:00 - */ - function max () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var latestTimestamp = Math.max.apply(null, dates); - return new Date(latestTimestamp) - } - - var max_1 = max; - - /** - * @category Common Helpers - * @summary Return the earliest of the given dates. - * - * @description - * Return the earliest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the earliest of the dates - * - * @example - * // Which of these dates is the earliest? - * var result = min( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Wed Feb 11 1987 00:00:00 - */ - function min () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var earliestTimestamp = Math.min.apply(null, dates); - return new Date(earliestTimestamp) - } - - var min_1 = min; - - /** - * @category Day Helpers - * @summary Set the day of the month to the given date. - * - * @description - * Set the day of the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfMonth - the day of the month of the new date - * @returns {Date} the new date with the day of the month setted - * - * @example - * // Set the 30th day of the month to 1 September 2014: - * var result = setDate(new Date(2014, 8, 1), 30) - * //=> Tue Sep 30 2014 00:00:00 - */ - function setDate (dirtyDate, dirtyDayOfMonth) { - var date = parse_1(dirtyDate); - var dayOfMonth = Number(dirtyDayOfMonth); - date.setDate(dayOfMonth); - return date - } - - var set_date = setDate; - - /** - * @category Weekday Helpers - * @summary Set the day of the week to the given date. - * - * @description - * Set the day of the week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the week of the new date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the new date with the day of the week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If week starts with Monday, set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0, {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ - function setDay (dirtyDate, dirtyDay, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = date.getDay(); - - var remainder = day % 7; - var dayIndex = (remainder + 7) % 7; - - var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; - return add_days(date, diff) - } - - var set_day = setDay; - - /** - * @category Day Helpers - * @summary Set the day of the year to the given date. - * - * @description - * Set the day of the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfYear - the day of the year of the new date - * @returns {Date} the new date with the day of the year setted - * - * @example - * // Set the 2nd day of the year to 2 July 2014: - * var result = setDayOfYear(new Date(2014, 6, 2), 2) - * //=> Thu Jan 02 2014 00:00:00 - */ - function setDayOfYear (dirtyDate, dirtyDayOfYear) { - var date = parse_1(dirtyDate); - var dayOfYear = Number(dirtyDayOfYear); - date.setMonth(0); - date.setDate(dayOfYear); - return date - } - - var set_day_of_year = setDayOfYear; - - /** - * @category Hour Helpers - * @summary Set the hours to the given date. - * - * @description - * Set the hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} hours - the hours of the new date - * @returns {Date} the new date with the hours setted - * - * @example - * // Set 4 hours to 1 September 2014 11:30:00: - * var result = setHours(new Date(2014, 8, 1, 11, 30), 4) - * //=> Mon Sep 01 2014 04:30:00 - */ - function setHours (dirtyDate, dirtyHours) { - var date = parse_1(dirtyDate); - var hours = Number(dirtyHours); - date.setHours(hours); - return date - } - - var set_hours = setHours; - - /** - * @category Weekday Helpers - * @summary Set the day of the ISO week to the given date. - * - * @description - * Set the day of the ISO week to the given date. - * ISO week starts with Monday. - * 7 is the index of Sunday, 1 is the index of Monday etc. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the ISO week of the new date - * @returns {Date} the new date with the day of the ISO week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setISODay(new Date(2014, 8, 1), 7) - * //=> Sun Sep 07 2014 00:00:00 - */ - function setISODay (dirtyDate, dirtyDay) { - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = get_iso_day(date); - var diff = day - currentDay; - return add_days(date, diff) - } - - var set_iso_day = setISODay; - - /** - * @category ISO Week Helpers - * @summary Set the ISO week to the given date. - * - * @description - * Set the ISO week to the given date, saving the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoWeek - the ISO week of the new date - * @returns {Date} the new date with the ISO week setted - * - * @example - * // Set the 53rd ISO week to 7 August 2004: - * var result = setISOWeek(new Date(2004, 7, 7), 53) - * //=> Sat Jan 01 2005 00:00:00 - */ - function setISOWeek (dirtyDate, dirtyISOWeek) { - var date = parse_1(dirtyDate); - var isoWeek = Number(dirtyISOWeek); - var diff = get_iso_week(date) - isoWeek; - date.setDate(date.getDate() - diff * 7); - return date - } - - var set_iso_week = setISOWeek; - - /** - * @category Millisecond Helpers - * @summary Set the milliseconds to the given date. - * - * @description - * Set the milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} milliseconds - the milliseconds of the new date - * @returns {Date} the new date with the milliseconds setted - * - * @example - * // Set 300 milliseconds to 1 September 2014 11:30:40.500: - * var result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300) - * //=> Mon Sep 01 2014 11:30:40.300 - */ - function setMilliseconds (dirtyDate, dirtyMilliseconds) { - var date = parse_1(dirtyDate); - var milliseconds = Number(dirtyMilliseconds); - date.setMilliseconds(milliseconds); - return date - } - - var set_milliseconds = setMilliseconds; - - /** - * @category Minute Helpers - * @summary Set the minutes to the given date. - * - * @description - * Set the minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} minutes - the minutes of the new date - * @returns {Date} the new date with the minutes setted - * - * @example - * // Set 45 minutes to 1 September 2014 11:30:40: - * var result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:45:40 - */ - function setMinutes (dirtyDate, dirtyMinutes) { - var date = parse_1(dirtyDate); - var minutes = Number(dirtyMinutes); - date.setMinutes(minutes); - return date - } - - var set_minutes = setMinutes; - - /** - * @category Month Helpers - * @summary Set the month to the given date. - * - * @description - * Set the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} month - the month of the new date - * @returns {Date} the new date with the month setted - * - * @example - * // Set February to 1 September 2014: - * var result = setMonth(new Date(2014, 8, 1), 1) - * //=> Sat Feb 01 2014 00:00:00 - */ - function setMonth (dirtyDate, dirtyMonth) { - var date = parse_1(dirtyDate); - var month = Number(dirtyMonth); - var year = date.getFullYear(); - var day = date.getDate(); - - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(year, month, 15); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(month, Math.min(day, daysInMonth)); - return date - } - - var set_month = setMonth; - - /** - * @category Quarter Helpers - * @summary Set the year quarter to the given date. - * - * @description - * Set the year quarter to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} quarter - the quarter of the new date - * @returns {Date} the new date with the quarter setted - * - * @example - * // Set the 2nd quarter to 2 July 2014: - * var result = setQuarter(new Date(2014, 6, 2), 2) - * //=> Wed Apr 02 2014 00:00:00 - */ - function setQuarter (dirtyDate, dirtyQuarter) { - var date = parse_1(dirtyDate); - var quarter = Number(dirtyQuarter); - var oldQuarter = Math.floor(date.getMonth() / 3) + 1; - var diff = quarter - oldQuarter; - return set_month(date, date.getMonth() + diff * 3) - } - - var set_quarter = setQuarter; - - /** - * @category Second Helpers - * @summary Set the seconds to the given date. - * - * @description - * Set the seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} seconds - the seconds of the new date - * @returns {Date} the new date with the seconds setted - * - * @example - * // Set 45 seconds to 1 September 2014 11:30:40: - * var result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:30:45 - */ - function setSeconds (dirtyDate, dirtySeconds) { - var date = parse_1(dirtyDate); - var seconds = Number(dirtySeconds); - date.setSeconds(seconds); - return date - } - - var set_seconds = setSeconds; - - /** - * @category Year Helpers - * @summary Set the year to the given date. - * - * @description - * Set the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} year - the year of the new date - * @returns {Date} the new date with the year setted - * - * @example - * // Set year 2013 to 1 September 2014: - * var result = setYear(new Date(2014, 8, 1), 2013) - * //=> Sun Sep 01 2013 00:00:00 - */ - function setYear (dirtyDate, dirtyYear) { - var date = parse_1(dirtyDate); - var year = Number(dirtyYear); - date.setFullYear(year); - return date - } - - var set_year = setYear; - - /** - * @category Month Helpers - * @summary Return the start of a month for the given date. - * - * @description - * Return the start of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a month - * - * @example - * // The start of a month for 2 September 2014 11:55:00: - * var result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - date.setDate(1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_month = startOfMonth; - - /** - * @category Day Helpers - * @summary Return the start of today. - * - * @description - * Return the start of today. - * - * @returns {Date} the start of today - * - * @example - * // If today is 6 October 2014: - * var result = startOfToday() - * //=> Mon Oct 6 2014 00:00:00 - */ - function startOfToday () { - return start_of_day(new Date()) - } - - var start_of_today = startOfToday; - - /** - * @category Day Helpers - * @summary Return the start of tomorrow. - * - * @description - * Return the start of tomorrow. - * - * @returns {Date} the start of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = startOfTomorrow() - * //=> Tue Oct 7 2014 00:00:00 - */ - function startOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_tomorrow = startOfTomorrow; - - /** - * @category Day Helpers - * @summary Return the start of yesterday. - * - * @description - * Return the start of yesterday. - * - * @returns {Date} the start of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = startOfYesterday() - * //=> Sun Oct 5 2014 00:00:00 - */ - function startOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_yesterday = startOfYesterday; - - /** - * @category Day Helpers - * @summary Subtract the specified number of days from the given date. - * - * @description - * Subtract the specified number of days from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be subtracted - * @returns {Date} the new date with the days subtracted - * - * @example - * // Subtract 10 days from 1 September 2014: - * var result = subDays(new Date(2014, 8, 1), 10) - * //=> Fri Aug 22 2014 00:00:00 - */ - function subDays (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_days(dirtyDate, -amount) - } - - var sub_days = subDays; - - /** - * @category Hour Helpers - * @summary Subtract the specified number of hours from the given date. - * - * @description - * Subtract the specified number of hours from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be subtracted - * @returns {Date} the new date with the hours subtracted - * - * @example - * // Subtract 2 hours from 11 July 2014 01:00:00: - * var result = subHours(new Date(2014, 6, 11, 1, 0), 2) - * //=> Thu Jul 10 2014 23:00:00 - */ - function subHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_hours(dirtyDate, -amount) - } - - var sub_hours = subHours; - - /** - * @category Millisecond Helpers - * @summary Subtract the specified number of milliseconds from the given date. - * - * @description - * Subtract the specified number of milliseconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be subtracted - * @returns {Date} the new date with the milliseconds subtracted - * - * @example - * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: - * var result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:29.250 - */ - function subMilliseconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, -amount) - } - - var sub_milliseconds = subMilliseconds; - - /** - * @category Minute Helpers - * @summary Subtract the specified number of minutes from the given date. - * - * @description - * Subtract the specified number of minutes from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be subtracted - * @returns {Date} the new date with the mintues subtracted - * - * @example - * // Subtract 30 minutes from 10 July 2014 12:00:00: - * var result = subMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 11:30:00 - */ - function subMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_minutes(dirtyDate, -amount) - } - - var sub_minutes = subMinutes; - - /** - * @category Month Helpers - * @summary Subtract the specified number of months from the given date. - * - * @description - * Subtract the specified number of months from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be subtracted - * @returns {Date} the new date with the months subtracted - * - * @example - * // Subtract 5 months from 1 February 2015: - * var result = subMonths(new Date(2015, 1, 1), 5) - * //=> Mon Sep 01 2014 00:00:00 - */ - function subMonths (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, -amount) - } - - var sub_months = subMonths; - - /** - * @category Quarter Helpers - * @summary Subtract the specified number of year quarters from the given date. - * - * @description - * Subtract the specified number of year quarters from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be subtracted - * @returns {Date} the new date with the quarters subtracted - * - * @example - * // Subtract 3 quarters from 1 September 2014: - * var result = subQuarters(new Date(2014, 8, 1), 3) - * //=> Sun Dec 01 2013 00:00:00 - */ - function subQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_quarters(dirtyDate, -amount) - } - - var sub_quarters = subQuarters; - - /** - * @category Second Helpers - * @summary Subtract the specified number of seconds from the given date. - * - * @description - * Subtract the specified number of seconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be subtracted - * @returns {Date} the new date with the seconds subtracted - * - * @example - * // Subtract 30 seconds from 10 July 2014 12:45:00: - * var result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:44:30 - */ - function subSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_seconds(dirtyDate, -amount) - } - - var sub_seconds = subSeconds; - - /** - * @category Week Helpers - * @summary Subtract the specified number of weeks from the given date. - * - * @description - * Subtract the specified number of weeks from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be subtracted - * @returns {Date} the new date with the weeks subtracted - * - * @example - * // Subtract 4 weeks from 1 September 2014: - * var result = subWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Aug 04 2014 00:00:00 - */ - function subWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_weeks(dirtyDate, -amount) - } - - var sub_weeks = subWeeks; - - /** - * @category Year Helpers - * @summary Subtract the specified number of years from the given date. - * - * @description - * Subtract the specified number of years from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be subtracted - * @returns {Date} the new date with the years subtracted - * - * @example - * // Subtract 5 years from 1 September 2014: - * var result = subYears(new Date(2014, 8, 1), 5) - * //=> Tue Sep 01 2009 00:00:00 - */ - function subYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_years(dirtyDate, -amount) - } - - var sub_years = subYears; - - var dateFns = { - addDays: add_days, - addHours: add_hours, - addISOYears: add_iso_years, - addMilliseconds: add_milliseconds, - addMinutes: add_minutes, - addMonths: add_months, - addQuarters: add_quarters, - addSeconds: add_seconds, - addWeeks: add_weeks, - addYears: add_years, - areRangesOverlapping: are_ranges_overlapping, - closestIndexTo: closest_index_to, - closestTo: closest_to, - compareAsc: compare_asc, - compareDesc: compare_desc, - differenceInCalendarDays: difference_in_calendar_days, - differenceInCalendarISOWeeks: difference_in_calendar_iso_weeks, - differenceInCalendarISOYears: difference_in_calendar_iso_years, - differenceInCalendarMonths: difference_in_calendar_months, - differenceInCalendarQuarters: difference_in_calendar_quarters, - differenceInCalendarWeeks: difference_in_calendar_weeks, - differenceInCalendarYears: difference_in_calendar_years, - differenceInDays: difference_in_days, - differenceInHours: difference_in_hours, - differenceInISOYears: difference_in_iso_years, - differenceInMilliseconds: difference_in_milliseconds, - differenceInMinutes: difference_in_minutes, - differenceInMonths: difference_in_months, - differenceInQuarters: difference_in_quarters, - differenceInSeconds: difference_in_seconds, - differenceInWeeks: difference_in_weeks, - differenceInYears: difference_in_years, - distanceInWords: distance_in_words, - distanceInWordsStrict: distance_in_words_strict, - distanceInWordsToNow: distance_in_words_to_now, - eachDay: each_day, - endOfDay: end_of_day, - endOfHour: end_of_hour, - endOfISOWeek: end_of_iso_week, - endOfISOYear: end_of_iso_year, - endOfMinute: end_of_minute, - endOfMonth: end_of_month, - endOfQuarter: end_of_quarter, - endOfSecond: end_of_second, - endOfToday: end_of_today, - endOfTomorrow: end_of_tomorrow, - endOfWeek: end_of_week, - endOfYear: end_of_year, - endOfYesterday: end_of_yesterday, - format: format_1, - getDate: get_date, - getDay: get_day, - getDayOfYear: get_day_of_year, - getDaysInMonth: get_days_in_month, - getDaysInYear: get_days_in_year, - getHours: get_hours, - getISODay: get_iso_day, - getISOWeek: get_iso_week, - getISOWeeksInYear: get_iso_weeks_in_year, - getISOYear: get_iso_year, - getMilliseconds: get_milliseconds, - getMinutes: get_minutes, - getMonth: get_month, - getOverlappingDaysInRanges: get_overlapping_days_in_ranges, - getQuarter: get_quarter, - getSeconds: get_seconds, - getTime: get_time, - getYear: get_year, - isAfter: is_after, - isBefore: is_before, - isDate: is_date, - isEqual: is_equal, - isFirstDayOfMonth: is_first_day_of_month, - isFriday: is_friday, - isFuture: is_future, - isLastDayOfMonth: is_last_day_of_month, - isLeapYear: is_leap_year, - isMonday: is_monday, - isPast: is_past, - isSameDay: is_same_day, - isSameHour: is_same_hour, - isSameISOWeek: is_same_iso_week, - isSameISOYear: is_same_iso_year, - isSameMinute: is_same_minute, - isSameMonth: is_same_month, - isSameQuarter: is_same_quarter, - isSameSecond: is_same_second, - isSameWeek: is_same_week, - isSameYear: is_same_year, - isSaturday: is_saturday, - isSunday: is_sunday, - isThisHour: is_this_hour, - isThisISOWeek: is_this_iso_week, - isThisISOYear: is_this_iso_year, - isThisMinute: is_this_minute, - isThisMonth: is_this_month, - isThisQuarter: is_this_quarter, - isThisSecond: is_this_second, - isThisWeek: is_this_week, - isThisYear: is_this_year, - isThursday: is_thursday, - isToday: is_today, - isTomorrow: is_tomorrow, - isTuesday: is_tuesday, - isValid: is_valid, - isWednesday: is_wednesday, - isWeekend: is_weekend, - isWithinRange: is_within_range, - isYesterday: is_yesterday, - lastDayOfISOWeek: last_day_of_iso_week, - lastDayOfISOYear: last_day_of_iso_year, - lastDayOfMonth: last_day_of_month, - lastDayOfQuarter: last_day_of_quarter, - lastDayOfWeek: last_day_of_week, - lastDayOfYear: last_day_of_year, - max: max_1, - min: min_1, - parse: parse_1, - setDate: set_date, - setDay: set_day, - setDayOfYear: set_day_of_year, - setHours: set_hours, - setISODay: set_iso_day, - setISOWeek: set_iso_week, - setISOYear: set_iso_year, - setMilliseconds: set_milliseconds, - setMinutes: set_minutes, - setMonth: set_month, - setQuarter: set_quarter, - setSeconds: set_seconds, - setYear: set_year, - startOfDay: start_of_day, - startOfHour: start_of_hour, - startOfISOWeek: start_of_iso_week, - startOfISOYear: start_of_iso_year, - startOfMinute: start_of_minute, - startOfMonth: start_of_month, - startOfQuarter: start_of_quarter, - startOfSecond: start_of_second, - startOfToday: start_of_today, - startOfTomorrow: start_of_tomorrow, - startOfWeek: start_of_week, - startOfYear: start_of_year, - startOfYesterday: start_of_yesterday, - subDays: sub_days, - subHours: sub_hours, - subISOYears: sub_iso_years, - subMilliseconds: sub_milliseconds, - subMinutes: sub_minutes, - subMonths: sub_months, - subQuarters: sub_quarters, - subSeconds: sub_seconds, - subWeeks: sub_weeks, - subYears: sub_years - }; - - const user = "user"; - - const date$2 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo$2 = `Sunnyvale ${user} ${date$2}`; - - const date$1 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo$1 = `@foo/lib/a ${date$1}`; - - const date = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo = `@foo/lib/a/a/a ${date}`; - - const fum = 'Wonderland'; - - var hello = 'Hello'; - - const name = 'Alice'; - - const json_key = "json_value"; - - console.log( - `${hello}, ${name} in ${fum} ${foo$2} ${foo$1} ${foo} ${far_a} ${far_a_b_c} ${json_key}`); - - // Test for sequences = false - class A { - a() { - return document.a; - } - } - function inline_me() { - return 'abc'; - } - console.error(new A().a(), inline_me(), some_global_var.thing); - - exports.A = A; - - Object.defineProperty(exports, '__esModule', { value: true }); - - return exports; - -}({}, runtime_name_of_global_var)); -//# sourceMappingURL=bundle.iife.js.map
diff --git a/packages/rollup/test/integration/golden.system.js.map.sha256_ b/packages/rollup/test/integration/golden.system.js.map.sha256_ deleted file mode 100644 index d86f35c..0000000 --- a/packages/rollup/test/integration/golden.system.js.map.sha256_ +++ /dev/null
@@ -1 +0,0 @@ -2d18f75b03dbb3e5495b49050f0f2767e21bf8ce9495ed9d446c48f5e2081976 \ No newline at end of file
diff --git a/packages/rollup/test/integration/golden.system.js_ b/packages/rollup/test/integration/golden.system.js_ deleted file mode 100644 index 69f3678..0000000 --- a/packages/rollup/test/integration/golden.system.js_ +++ /dev/null
@@ -1,5687 +0,0 @@ -/** - * @license A dummy license banner that goes at the top of the file. - * This is version <unknown> - */ - -System.register('bundle', ['some_global_var'], function (exports) { - 'use strict'; - var thing; - return { - setters: [function (module) { - thing = module.thing; - }], - execute: function () { - - var far_a = `@far/a`; - - var far_a_b_c = `@far/a/b/c`; - - var MILLISECONDS_IN_MINUTE$6 = 60000; - - /** - * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. - * They usually appear for dates that denote time before the timezones were introduced - * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 - * and GMT+01:00:00 after that date) - * - * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above, - * which would lead to incorrect calculations. - * - * This function returns the timezone offset in milliseconds that takes seconds in account. - */ - var getTimezoneOffsetInMilliseconds = function getTimezoneOffsetInMilliseconds (dirtyDate) { - var date = new Date(dirtyDate.getTime()); - var baseTimezoneOffset = date.getTimezoneOffset(); - date.setSeconds(0, 0); - var millisecondsPartOfTimezoneOffset = date.getTime() % MILLISECONDS_IN_MINUTE$6; - - return baseTimezoneOffset * MILLISECONDS_IN_MINUTE$6 + millisecondsPartOfTimezoneOffset - }; - - /** - * @category Common Helpers - * @summary Is the given argument an instance of Date? - * - * @description - * Is the given argument an instance of Date? - * - * @param {*} argument - the argument to check - * @returns {Boolean} the given argument is an instance of Date - * - * @example - * // Is 'mayonnaise' a Date? - * var result = isDate('mayonnaise') - * //=> false - */ - function isDate (argument) { - return argument instanceof Date - } - - var is_date = isDate; - - var MILLISECONDS_IN_HOUR$2 = 3600000; - var MILLISECONDS_IN_MINUTE$5 = 60000; - var DEFAULT_ADDITIONAL_DIGITS = 2; - - var parseTokenDateTimeDelimeter = /[T ]/; - var parseTokenPlainTime = /:/; - - // year tokens - var parseTokenYY = /^(\d{2})$/; - var parseTokensYYY = [ - /^([+-]\d{2})$/, // 0 additional digits - /^([+-]\d{3})$/, // 1 additional digit - /^([+-]\d{4})$/ // 2 additional digits - ]; - - var parseTokenYYYY = /^(\d{4})/; - var parseTokensYYYYY = [ - /^([+-]\d{4})/, // 0 additional digits - /^([+-]\d{5})/, // 1 additional digit - /^([+-]\d{6})/ // 2 additional digits - ]; - - // date tokens - var parseTokenMM = /^-(\d{2})$/; - var parseTokenDDD = /^-?(\d{3})$/; - var parseTokenMMDD = /^-?(\d{2})-?(\d{2})$/; - var parseTokenWww = /^-?W(\d{2})$/; - var parseTokenWwwD = /^-?W(\d{2})-?(\d{1})$/; - - // time tokens - var parseTokenHH = /^(\d{2}([.,]\d*)?)$/; - var parseTokenHHMM = /^(\d{2}):?(\d{2}([.,]\d*)?)$/; - var parseTokenHHMMSS = /^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/; - - // timezone tokens - var parseTokenTimezone = /([Z+-].*)$/; - var parseTokenTimezoneZ = /^(Z)$/; - var parseTokenTimezoneHH = /^([+-])(\d{2})$/; - var parseTokenTimezoneHHMM = /^([+-])(\d{2}):?(\d{2})$/; - - /** - * @category Common Helpers - * @summary Convert the given argument to an instance of Date. - * - * @description - * Convert the given argument to an instance of Date. - * - * If the argument is an instance of Date, the function returns its clone. - * - * If the argument is a number, it is treated as a timestamp. - * - * If an argument is a string, the function tries to parse it. - * Function accepts complete ISO 8601 formats as well as partial implementations. - * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 - * - * If all above fails, the function passes the given argument to Date constructor. - * - * @param {Date|String|Number} argument - the value to convert - * @param {Object} [options] - the object with options - * @param {0 | 1 | 2} [options.additionalDigits=2] - the additional number of digits in the extended year format - * @returns {Date} the parsed date in the local time zone - * - * @example - * // Convert string '2014-02-11T11:30:30' to date: - * var result = parse('2014-02-11T11:30:30') - * //=> Tue Feb 11 2014 11:30:30 - * - * @example - * // Parse string '+02014101', - * // if the additional number of digits in the extended year format is 1: - * var result = parse('+02014101', {additionalDigits: 1}) - * //=> Fri Apr 11 2014 00:00:00 - */ - function parse (argument, dirtyOptions) { - if (is_date(argument)) { - // Prevent the date to lose the milliseconds when passed to new Date() in IE10 - return new Date(argument.getTime()) - } else if (typeof argument !== 'string') { - return new Date(argument) - } - - var options = dirtyOptions || {}; - var additionalDigits = options.additionalDigits; - if (additionalDigits == null) { - additionalDigits = DEFAULT_ADDITIONAL_DIGITS; - } else { - additionalDigits = Number(additionalDigits); - } - - var dateStrings = splitDateString(argument); - - var parseYearResult = parseYear(dateStrings.date, additionalDigits); - var year = parseYearResult.year; - var restDateString = parseYearResult.restDateString; - - var date = parseDate(restDateString, year); - - if (date) { - var timestamp = date.getTime(); - var time = 0; - var offset; - - if (dateStrings.time) { - time = parseTime(dateStrings.time); - } - - if (dateStrings.timezone) { - offset = parseTimezone(dateStrings.timezone) * MILLISECONDS_IN_MINUTE$5; - } else { - var fullTime = timestamp + time; - var fullTimeDate = new Date(fullTime); - - offset = getTimezoneOffsetInMilliseconds(fullTimeDate); - - // Adjust time when it's coming from DST - var fullTimeDateNextDay = new Date(fullTime); - fullTimeDateNextDay.setDate(fullTimeDate.getDate() + 1); - var offsetDiff = - getTimezoneOffsetInMilliseconds(fullTimeDateNextDay) - - getTimezoneOffsetInMilliseconds(fullTimeDate); - if (offsetDiff > 0) { - offset += offsetDiff; - } - } - - return new Date(timestamp + time + offset) - } else { - return new Date(argument) - } - } - - function splitDateString (dateString) { - var dateStrings = {}; - var array = dateString.split(parseTokenDateTimeDelimeter); - var timeString; - - if (parseTokenPlainTime.test(array[0])) { - dateStrings.date = null; - timeString = array[0]; - } else { - dateStrings.date = array[0]; - timeString = array[1]; - } - - if (timeString) { - var token = parseTokenTimezone.exec(timeString); - if (token) { - dateStrings.time = timeString.replace(token[1], ''); - dateStrings.timezone = token[1]; - } else { - dateStrings.time = timeString; - } - } - - return dateStrings - } - - function parseYear (dateString, additionalDigits) { - var parseTokenYYY = parseTokensYYY[additionalDigits]; - var parseTokenYYYYY = parseTokensYYYYY[additionalDigits]; - - var token; - - // YYYY or ±YYYYY - token = parseTokenYYYY.exec(dateString) || parseTokenYYYYY.exec(dateString); - if (token) { - var yearString = token[1]; - return { - year: parseInt(yearString, 10), - restDateString: dateString.slice(yearString.length) - } - } - - // YY or ±YYY - token = parseTokenYY.exec(dateString) || parseTokenYYY.exec(dateString); - if (token) { - var centuryString = token[1]; - return { - year: parseInt(centuryString, 10) * 100, - restDateString: dateString.slice(centuryString.length) - } - } - - // Invalid ISO-formatted year - return { - year: null - } - } - - function parseDate (dateString, year) { - // Invalid ISO-formatted year - if (year === null) { - return null - } - - var token; - var date; - var month; - var week; - - // YYYY - if (dateString.length === 0) { - date = new Date(0); - date.setUTCFullYear(year); - return date - } - - // YYYY-MM - token = parseTokenMM.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - date.setUTCFullYear(year, month); - return date - } - - // YYYY-DDD or YYYYDDD - token = parseTokenDDD.exec(dateString); - if (token) { - date = new Date(0); - var dayOfYear = parseInt(token[1], 10); - date.setUTCFullYear(year, 0, dayOfYear); - return date - } - - // YYYY-MM-DD or YYYYMMDD - token = parseTokenMMDD.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - var day = parseInt(token[2], 10); - date.setUTCFullYear(year, month, day); - return date - } - - // YYYY-Www or YYYYWww - token = parseTokenWww.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - return dayOfISOYear(year, week) - } - - // YYYY-Www-D or YYYYWwwD - token = parseTokenWwwD.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - var dayOfWeek = parseInt(token[2], 10) - 1; - return dayOfISOYear(year, week, dayOfWeek) - } - - // Invalid ISO-formatted date - return null - } - - function parseTime (timeString) { - var token; - var hours; - var minutes; - - // hh - token = parseTokenHH.exec(timeString); - if (token) { - hours = parseFloat(token[1].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 - } - - // hh:mm or hhmm - token = parseTokenHHMM.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseFloat(token[2].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 - } - - // hh:mm:ss or hhmmss - token = parseTokenHHMMSS.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseInt(token[2], 10); - var seconds = parseFloat(token[3].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 + - seconds * 1000 - } - - // Invalid ISO-formatted time - return null - } - - function parseTimezone (timezoneString) { - var token; - var absoluteOffset; - - // Z - token = parseTokenTimezoneZ.exec(timezoneString); - if (token) { - return 0 - } - - // ±hh - token = parseTokenTimezoneHH.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60; - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - // ±hh:mm or ±hhmm - token = parseTokenTimezoneHHMM.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60 + parseInt(token[3], 10); - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - return 0 - } - - function dayOfISOYear (isoYear, week, day) { - week = week || 0; - day = day || 0; - var date = new Date(0); - date.setUTCFullYear(isoYear, 0, 4); - var fourthOfJanuaryDay = date.getUTCDay() || 7; - var diff = week * 7 + day + 1 - fourthOfJanuaryDay; - date.setUTCDate(date.getUTCDate() + diff); - return date - } - - var parse_1 = parse; - - /** - * @category Day Helpers - * @summary Add the specified number of days to the given date. - * - * @description - * Add the specified number of days to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be added - * @returns {Date} the new date with the days added - * - * @example - * // Add 10 days to 1 September 2014: - * var result = addDays(new Date(2014, 8, 1), 10) - * //=> Thu Sep 11 2014 00:00:00 - */ - function addDays (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - date.setDate(date.getDate() + amount); - return date - } - - var add_days = addDays; - - /** - * @category Millisecond Helpers - * @summary Add the specified number of milliseconds to the given date. - * - * @description - * Add the specified number of milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be added - * @returns {Date} the new date with the milliseconds added - * - * @example - * // Add 750 milliseconds to 10 July 2014 12:45:30.000: - * var result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:30.750 - */ - function addMilliseconds (dirtyDate, dirtyAmount) { - var timestamp = parse_1(dirtyDate).getTime(); - var amount = Number(dirtyAmount); - return new Date(timestamp + amount) - } - - var add_milliseconds = addMilliseconds; - - var MILLISECONDS_IN_HOUR$1 = 3600000; - - /** - * @category Hour Helpers - * @summary Add the specified number of hours to the given date. - * - * @description - * Add the specified number of hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be added - * @returns {Date} the new date with the hours added - * - * @example - * // Add 2 hours to 10 July 2014 23:00:00: - * var result = addHours(new Date(2014, 6, 10, 23, 0), 2) - * //=> Fri Jul 11 2014 01:00:00 - */ - function addHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR$1) - } - - var add_hours = addHours; - - /** - * @category Week Helpers - * @summary Return the start of a week for the given date. - * - * @description - * Return the start of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the start of a week - * - * @example - * // The start of a week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - - date.setDate(date.getDate() - diff); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_week = startOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the start of an ISO week for the given date. - * - * @description - * Return the start of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO week - * - * @example - * // The start of an ISO week for 2 September 2014 11:55:00: - * var result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfISOWeek (dirtyDate) { - return start_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var start_of_iso_week = startOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the ISO week-numbering year of the given date. - * - * @description - * Get the ISO week-numbering year of the given date, - * which always starts 3 days before the year's first Thursday. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week-numbering year - * - * @example - * // Which ISO-week numbering year is 2 January 2005? - * var result = getISOYear(new Date(2005, 0, 2)) - * //=> 2004 - */ - function getISOYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var startOfNextYear = start_of_iso_week(fourthOfJanuaryOfNextYear); - - var fourthOfJanuaryOfThisYear = new Date(0); - fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); - fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); - var startOfThisYear = start_of_iso_week(fourthOfJanuaryOfThisYear); - - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1 - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year - } else { - return year - 1 - } - } - - var get_iso_year = getISOYear; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the start of an ISO week-numbering year for the given date. - * - * @description - * Return the start of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO year - * - * @example - * // The start of an ISO week-numbering year for 2 July 2005: - * var result = startOfISOYear(new Date(2005, 6, 2)) - * //=> Mon Jan 03 2005 00:00:00 - */ - function startOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - return date - } - - var start_of_iso_year = startOfISOYear; - - /** - * @category Day Helpers - * @summary Return the start of a day for the given date. - * - * @description - * Return the start of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a day - * - * @example - * // The start of a day for 2 September 2014 11:55:00: - * var result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 00:00:00 - */ - function startOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_day = startOfDay; - - var MILLISECONDS_IN_MINUTE$4 = 60000; - var MILLISECONDS_IN_DAY$1 = 86400000; - - /** - * @category Day Helpers - * @summary Get the number of calendar days between the given dates. - * - * @description - * Get the number of calendar days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar days - * - * @example - * // How many calendar days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInCalendarDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 366 - */ - function differenceInCalendarDays (dirtyDateLeft, dirtyDateRight) { - var startOfDayLeft = start_of_day(dirtyDateLeft); - var startOfDayRight = start_of_day(dirtyDateRight); - - var timestampLeft = startOfDayLeft.getTime() - - startOfDayLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - var timestampRight = startOfDayRight.getTime() - - startOfDayRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a day is not constant - // (e.g. it's different in the day of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY$1) - } - - var difference_in_calendar_days = differenceInCalendarDays; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Set the ISO week-numbering year to the given date. - * - * @description - * Set the ISO week-numbering year to the given date, - * saving the week number and the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoYear - the ISO week-numbering year of the new date - * @returns {Date} the new date with the ISO week-numbering year setted - * - * @example - * // Set ISO week-numbering year 2007 to 29 December 2008: - * var result = setISOYear(new Date(2008, 11, 29), 2007) - * //=> Mon Jan 01 2007 00:00:00 - */ - function setISOYear (dirtyDate, dirtyISOYear) { - var date = parse_1(dirtyDate); - var isoYear = Number(dirtyISOYear); - var diff = difference_in_calendar_days(date, start_of_iso_year(date)); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(isoYear, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - date = start_of_iso_year(fourthOfJanuary); - date.setDate(date.getDate() + diff); - return date - } - - var set_iso_year = setISOYear; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Add the specified number of ISO week-numbering years to the given date. - * - * @description - * Add the specified number of ISO week-numbering years to the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be added - * @returns {Date} the new date with the ISO week-numbering years added - * - * @example - * // Add 5 ISO week-numbering years to 2 July 2010: - * var result = addISOYears(new Date(2010, 6, 2), 5) - * //=> Fri Jun 26 2015 00:00:00 - */ - function addISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return set_iso_year(dirtyDate, get_iso_year(dirtyDate) + amount) - } - - var add_iso_years = addISOYears; - - var MILLISECONDS_IN_MINUTE$3 = 60000; - - /** - * @category Minute Helpers - * @summary Add the specified number of minutes to the given date. - * - * @description - * Add the specified number of minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be added - * @returns {Date} the new date with the minutes added - * - * @example - * // Add 30 minutes to 10 July 2014 12:00:00: - * var result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 12:30:00 - */ - function addMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE$3) - } - - var add_minutes = addMinutes; - - /** - * @category Month Helpers - * @summary Get the number of days in a month of the given date. - * - * @description - * Get the number of days in a month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a month - * - * @example - * // How many days are in February 2000? - * var result = getDaysInMonth(new Date(2000, 1)) - * //=> 29 - */ - function getDaysInMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - var monthIndex = date.getMonth(); - var lastDayOfMonth = new Date(0); - lastDayOfMonth.setFullYear(year, monthIndex + 1, 0); - lastDayOfMonth.setHours(0, 0, 0, 0); - return lastDayOfMonth.getDate() - } - - var get_days_in_month = getDaysInMonth; - - /** - * @category Month Helpers - * @summary Add the specified number of months to the given date. - * - * @description - * Add the specified number of months to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be added - * @returns {Date} the new date with the months added - * - * @example - * // Add 5 months to 1 September 2014: - * var result = addMonths(new Date(2014, 8, 1), 5) - * //=> Sun Feb 01 2015 00:00:00 - */ - function addMonths (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - var desiredMonth = date.getMonth() + amount; - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(date.getFullYear(), desiredMonth, 1); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(desiredMonth, Math.min(daysInMonth, date.getDate())); - return date - } - - var add_months = addMonths; - - /** - * @category Quarter Helpers - * @summary Add the specified number of year quarters to the given date. - * - * @description - * Add the specified number of year quarters to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be added - * @returns {Date} the new date with the quarters added - * - * @example - * // Add 1 quarter to 1 September 2014: - * var result = addQuarters(new Date(2014, 8, 1), 1) - * //=> Mon Dec 01 2014 00:00:00 - */ - function addQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var months = amount * 3; - return add_months(dirtyDate, months) - } - - var add_quarters = addQuarters; - - /** - * @category Second Helpers - * @summary Add the specified number of seconds to the given date. - * - * @description - * Add the specified number of seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be added - * @returns {Date} the new date with the seconds added - * - * @example - * // Add 30 seconds to 10 July 2014 12:45:00: - * var result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:45:30 - */ - function addSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * 1000) - } - - var add_seconds = addSeconds; - - /** - * @category Week Helpers - * @summary Add the specified number of weeks to the given date. - * - * @description - * Add the specified number of week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be added - * @returns {Date} the new date with the weeks added - * - * @example - * // Add 4 weeks to 1 September 2014: - * var result = addWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Sep 29 2014 00:00:00 - */ - function addWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var days = amount * 7; - return add_days(dirtyDate, days) - } - - var add_weeks = addWeeks; - - /** - * @category Year Helpers - * @summary Add the specified number of years to the given date. - * - * @description - * Add the specified number of years to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be added - * @returns {Date} the new date with the years added - * - * @example - * // Add 5 years to 1 September 2014: - * var result = addYears(new Date(2014, 8, 1), 5) - * //=> Sun Sep 01 2019 00:00:00 - */ - function addYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, amount * 12) - } - - var add_years = addYears; - - /** - * @category Range Helpers - * @summary Is the given date range overlapping with another date range? - * - * @description - * Is the given date range overlapping with another date range? - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Boolean} whether the date ranges are overlapping - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> true - * - * @example - * // For non-overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> false - */ - function areRangesOverlapping (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return initialStartTime < comparedEndTime && comparedStartTime < initialEndTime - } - - var are_ranges_overlapping = areRangesOverlapping; - - /** - * @category Common Helpers - * @summary Return an index of the closest date from the array comparing to the given date. - * - * @description - * Return an index of the closest date from the array comparing to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Number} an index of the date closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015? - * var dateToCompare = new Date(2015, 8, 6) - * var datesArray = [ - * new Date(2015, 0, 1), - * new Date(2016, 0, 1), - * new Date(2017, 0, 1) - * ] - * var result = closestIndexTo(dateToCompare, datesArray) - * //=> 1 - */ - function closestIndexTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate, index) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = index; - minDistance = distance; - } - }); - - return result - } - - var closest_index_to = closestIndexTo; - - /** - * @category Common Helpers - * @summary Return a date from the array closest to the given date. - * - * @description - * Return a date from the array closest to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Date} the date from the array closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030? - * var dateToCompare = new Date(2015, 8, 6) - * var result = closestTo(dateToCompare, [ - * new Date(2000, 0, 1), - * new Date(2030, 0, 1) - * ]) - * //=> Tue Jan 01 2030 00:00:00 - */ - function closestTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = currentDate; - minDistance = distance; - } - }); - - return result - } - - var closest_to = closestTo; - - /** - * @category Common Helpers - * @summary Compare the two dates and return -1, 0 or 1. - * - * @description - * Compare the two dates and return 1 if the first date is after the second, - * -1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989: - * var result = compareAsc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> -1 - * - * @example - * // Sort the array of dates: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareAsc) - * //=> [ - * // Wed Feb 11 1987 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Sun Jul 02 1995 00:00:00 - * // ] - */ - function compareAsc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft < timeRight) { - return -1 - } else if (timeLeft > timeRight) { - return 1 - } else { - return 0 - } - } - - var compare_asc = compareAsc; - - /** - * @category Common Helpers - * @summary Compare the two dates reverse chronologically and return -1, 0 or 1. - * - * @description - * Compare the two dates and return -1 if the first date is after the second, - * 1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989 reverse chronologically: - * var result = compareDesc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> 1 - * - * @example - * // Sort the array of dates in reverse chronological order: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareDesc) - * //=> [ - * // Sun Jul 02 1995 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Wed Feb 11 1987 00:00:00 - * // ] - */ - function compareDesc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft > timeRight) { - return -1 - } else if (timeLeft < timeRight) { - return 1 - } else { - return 0 - } - } - - var compare_desc = compareDesc; - - var MILLISECONDS_IN_MINUTE$2 = 60000; - var MILLISECONDS_IN_WEEK$3 = 604800000; - - /** - * @category ISO Week Helpers - * @summary Get the number of calendar ISO weeks between the given dates. - * - * @description - * Get the number of calendar ISO weeks between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO weeks - * - * @example - * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014? - * var result = differenceInCalendarISOWeeks( - * new Date(2014, 6, 21), - * new Date(2014, 6, 6) - * ) - * //=> 3 - */ - function differenceInCalendarISOWeeks (dirtyDateLeft, dirtyDateRight) { - var startOfISOWeekLeft = start_of_iso_week(dirtyDateLeft); - var startOfISOWeekRight = start_of_iso_week(dirtyDateRight); - - var timestampLeft = startOfISOWeekLeft.getTime() - - startOfISOWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - var timestampRight = startOfISOWeekRight.getTime() - - startOfISOWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$3) - } - - var difference_in_calendar_iso_weeks = differenceInCalendarISOWeeks; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of calendar ISO week-numbering years between the given dates. - * - * @description - * Get the number of calendar ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO week-numbering years - * - * @example - * // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012? - * var result = differenceInCalendarISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 2 - */ - function differenceInCalendarISOYears (dirtyDateLeft, dirtyDateRight) { - return get_iso_year(dirtyDateLeft) - get_iso_year(dirtyDateRight) - } - - var difference_in_calendar_iso_years = differenceInCalendarISOYears; - - /** - * @category Month Helpers - * @summary Get the number of calendar months between the given dates. - * - * @description - * Get the number of calendar months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar months - * - * @example - * // How many calendar months are between 31 January 2014 and 1 September 2014? - * var result = differenceInCalendarMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 8 - */ - function differenceInCalendarMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); - - return yearDiff * 12 + monthDiff - } - - var difference_in_calendar_months = differenceInCalendarMonths; - - /** - * @category Quarter Helpers - * @summary Get the year quarter of the given date. - * - * @description - * Get the year quarter of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the quarter - * - * @example - * // Which quarter is 2 July 2014? - * var result = getQuarter(new Date(2014, 6, 2)) - * //=> 3 - */ - function getQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var quarter = Math.floor(date.getMonth() / 3) + 1; - return quarter - } - - var get_quarter = getQuarter; - - /** - * @category Quarter Helpers - * @summary Get the number of calendar quarters between the given dates. - * - * @description - * Get the number of calendar quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar quarters - * - * @example - * // How many calendar quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInCalendarQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 3 - */ - function differenceInCalendarQuarters (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var quarterDiff = get_quarter(dateLeft) - get_quarter(dateRight); - - return yearDiff * 4 + quarterDiff - } - - var difference_in_calendar_quarters = differenceInCalendarQuarters; - - var MILLISECONDS_IN_MINUTE$1 = 60000; - var MILLISECONDS_IN_WEEK$2 = 604800000; - - /** - * @category Week Helpers - * @summary Get the number of calendar weeks between the given dates. - * - * @description - * Get the number of calendar weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Number} the number of calendar weeks - * - * @example - * // How many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 3 - * - * @example - * // If the week starts on Monday, - * // how many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5), - * {weekStartsOn: 1} - * ) - * //=> 2 - */ - function differenceInCalendarWeeks (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var startOfWeekLeft = start_of_week(dirtyDateLeft, dirtyOptions); - var startOfWeekRight = start_of_week(dirtyDateRight, dirtyOptions); - - var timestampLeft = startOfWeekLeft.getTime() - - startOfWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - var timestampRight = startOfWeekRight.getTime() - - startOfWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$2) - } - - var difference_in_calendar_weeks = differenceInCalendarWeeks; - - /** - * @category Year Helpers - * @summary Get the number of calendar years between the given dates. - * - * @description - * Get the number of calendar years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar years - * - * @example - * // How many calendar years are between 31 December 2013 and 11 February 2015? - * var result = differenceInCalendarYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ - function differenceInCalendarYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - return dateLeft.getFullYear() - dateRight.getFullYear() - } - - var difference_in_calendar_years = differenceInCalendarYears; - - /** - * @category Day Helpers - * @summary Get the number of full days between the given dates. - * - * @description - * Get the number of full days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full days - * - * @example - * // How many full days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 365 - */ - function differenceInDays (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_days(dateLeft, dateRight)); - dateLeft.setDate(dateLeft.getDate() - sign * difference); - - // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full - // If so, result must be decreased by 1 in absolute value - var isLastDayNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastDayNotFull) - } - - var difference_in_days = differenceInDays; - - /** - * @category Millisecond Helpers - * @summary Get the number of milliseconds between the given dates. - * - * @description - * Get the number of milliseconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of milliseconds - * - * @example - * // How many milliseconds are between - * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700? - * var result = differenceInMilliseconds( - * new Date(2014, 6, 2, 12, 30, 21, 700), - * new Date(2014, 6, 2, 12, 30, 20, 600) - * ) - * //=> 1100 - */ - function differenceInMilliseconds (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getTime() - dateRight.getTime() - } - - var difference_in_milliseconds = differenceInMilliseconds; - - var MILLISECONDS_IN_HOUR = 3600000; - - /** - * @category Hour Helpers - * @summary Get the number of hours between the given dates. - * - * @description - * Get the number of hours between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of hours - * - * @example - * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00? - * var result = differenceInHours( - * new Date(2014, 6, 2, 19, 0), - * new Date(2014, 6, 2, 6, 50) - * ) - * //=> 12 - */ - function differenceInHours (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_hours = differenceInHours; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Subtract the specified number of ISO week-numbering years from the given date. - * - * @description - * Subtract the specified number of ISO week-numbering years from the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be subtracted - * @returns {Date} the new date with the ISO week-numbering years subtracted - * - * @example - * // Subtract 5 ISO week-numbering years from 1 September 2014: - * var result = subISOYears(new Date(2014, 8, 1), 5) - * //=> Mon Aug 31 2009 00:00:00 - */ - function subISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_iso_years(dirtyDate, -amount) - } - - var sub_iso_years = subISOYears; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of full ISO week-numbering years between the given dates. - * - * @description - * Get the number of full ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full ISO week-numbering years - * - * @example - * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012? - * var result = differenceInISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 1 - */ - function differenceInISOYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_iso_years(dateLeft, dateRight)); - dateLeft = sub_iso_years(dateLeft, sign * difference); - - // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1 - // if last calendar ISO year is not full - // If so, result must be decreased by 1 in absolute value - var isLastISOYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastISOYearNotFull) - } - - var difference_in_iso_years = differenceInISOYears; - - var MILLISECONDS_IN_MINUTE = 60000; - - /** - * @category Minute Helpers - * @summary Get the number of minutes between the given dates. - * - * @description - * Get the number of minutes between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of minutes - * - * @example - * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00? - * var result = differenceInMinutes( - * new Date(2014, 6, 2, 12, 20, 0), - * new Date(2014, 6, 2, 12, 7, 59) - * ) - * //=> 12 - */ - function differenceInMinutes (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_minutes = differenceInMinutes; - - /** - * @category Month Helpers - * @summary Get the number of full months between the given dates. - * - * @description - * Get the number of full months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full months - * - * @example - * // How many full months are between 31 January 2014 and 1 September 2014? - * var result = differenceInMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 7 - */ - function differenceInMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_months(dateLeft, dateRight)); - dateLeft.setMonth(dateLeft.getMonth() - sign * difference); - - // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full - // If so, result must be decreased by 1 in absolute value - var isLastMonthNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastMonthNotFull) - } - - var difference_in_months = differenceInMonths; - - /** - * @category Quarter Helpers - * @summary Get the number of full quarters between the given dates. - * - * @description - * Get the number of full quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full quarters - * - * @example - * // How many full quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ - function differenceInQuarters (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_months(dirtyDateLeft, dirtyDateRight) / 3; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_quarters = differenceInQuarters; - - /** - * @category Second Helpers - * @summary Get the number of seconds between the given dates. - * - * @description - * Get the number of seconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of seconds - * - * @example - * // How many seconds are between - * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000? - * var result = differenceInSeconds( - * new Date(2014, 6, 2, 12, 30, 20, 0), - * new Date(2014, 6, 2, 12, 30, 7, 999) - * ) - * //=> 12 - */ - function differenceInSeconds (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / 1000; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_seconds = differenceInSeconds; - - /** - * @category Week Helpers - * @summary Get the number of full weeks between the given dates. - * - * @description - * Get the number of full weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full weeks - * - * @example - * // How many full weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 2 - */ - function differenceInWeeks (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_days(dirtyDateLeft, dirtyDateRight) / 7; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_weeks = differenceInWeeks; - - /** - * @category Year Helpers - * @summary Get the number of full years between the given dates. - * - * @description - * Get the number of full years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full years - * - * @example - * // How many full years are between 31 December 2013 and 11 February 2015? - * var result = differenceInYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 1 - */ - function differenceInYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_years(dateLeft, dateRight)); - dateLeft.setFullYear(dateLeft.getFullYear() - sign * difference); - - // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full - // If so, result must be decreased by 1 in absolute value - var isLastYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastYearNotFull) - } - - var difference_in_years = differenceInYears; - - function buildDistanceInWordsLocale () { - var distanceInWordsLocale = { - lessThanXSeconds: { - one: 'less than a second', - other: 'less than {{count}} seconds' - }, - - xSeconds: { - one: '1 second', - other: '{{count}} seconds' - }, - - halfAMinute: 'half a minute', - - lessThanXMinutes: { - one: 'less than a minute', - other: 'less than {{count}} minutes' - }, - - xMinutes: { - one: '1 minute', - other: '{{count}} minutes' - }, - - aboutXHours: { - one: 'about 1 hour', - other: 'about {{count}} hours' - }, - - xHours: { - one: '1 hour', - other: '{{count}} hours' - }, - - xDays: { - one: '1 day', - other: '{{count}} days' - }, - - aboutXMonths: { - one: 'about 1 month', - other: 'about {{count}} months' - }, - - xMonths: { - one: '1 month', - other: '{{count}} months' - }, - - aboutXYears: { - one: 'about 1 year', - other: 'about {{count}} years' - }, - - xYears: { - one: '1 year', - other: '{{count}} years' - }, - - overXYears: { - one: 'over 1 year', - other: 'over {{count}} years' - }, - - almostXYears: { - one: 'almost 1 year', - other: 'almost {{count}} years' - } - }; - - function localize (token, count, options) { - options = options || {}; - - var result; - if (typeof distanceInWordsLocale[token] === 'string') { - result = distanceInWordsLocale[token]; - } else if (count === 1) { - result = distanceInWordsLocale[token].one; - } else { - result = distanceInWordsLocale[token].other.replace('{{count}}', count); - } - - if (options.addSuffix) { - if (options.comparison > 0) { - return 'in ' + result - } else { - return result + ' ago' - } - } - - return result - } - - return { - localize: localize - } - } - - var build_distance_in_words_locale = buildDistanceInWordsLocale; - - var commonFormatterKeys = [ - 'M', 'MM', 'Q', 'D', 'DD', 'DDD', 'DDDD', 'd', - 'E', 'W', 'WW', 'YY', 'YYYY', 'GG', 'GGGG', - 'H', 'HH', 'h', 'hh', 'm', 'mm', - 's', 'ss', 'S', 'SS', 'SSS', - 'Z', 'ZZ', 'X', 'x' - ]; - - function buildFormattingTokensRegExp (formatters) { - var formatterKeys = []; - for (var key in formatters) { - if (formatters.hasOwnProperty(key)) { - formatterKeys.push(key); - } - } - - var formattingTokens = commonFormatterKeys - .concat(formatterKeys) - .sort() - .reverse(); - var formattingTokensRegExp = new RegExp( - '(\\[[^\\[]*\\])|(\\\\)?' + '(' + formattingTokens.join('|') + '|.)', 'g' - ); - - return formattingTokensRegExp - } - - var build_formatting_tokens_reg_exp = buildFormattingTokensRegExp; - - function buildFormatLocale () { - // Note: in English, the names of days of the week and months are capitalized. - // If you are making a new locale based on this one, check if the same is true for the language you're working on. - // Generally, formatted dates should look like they are in the middle of a sentence, - // e.g. in Spanish language the weekdays and months should be in the lowercase. - var months3char = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var monthsFull = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; - var weekdays2char = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']; - var weekdays3char = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - var weekdaysFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; - var meridiemUppercase = ['AM', 'PM']; - var meridiemLowercase = ['am', 'pm']; - var meridiemFull = ['a.m.', 'p.m.']; - - var formatters = { - // Month: Jan, Feb, ..., Dec - 'MMM': function (date) { - return months3char[date.getMonth()] - }, - - // Month: January, February, ..., December - 'MMMM': function (date) { - return monthsFull[date.getMonth()] - }, - - // Day of week: Su, Mo, ..., Sa - 'dd': function (date) { - return weekdays2char[date.getDay()] - }, - - // Day of week: Sun, Mon, ..., Sat - 'ddd': function (date) { - return weekdays3char[date.getDay()] - }, - - // Day of week: Sunday, Monday, ..., Saturday - 'dddd': function (date) { - return weekdaysFull[date.getDay()] - }, - - // AM, PM - 'A': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemUppercase[1] : meridiemUppercase[0] - }, - - // am, pm - 'a': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemLowercase[1] : meridiemLowercase[0] - }, - - // a.m., p.m. - 'aa': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemFull[1] : meridiemFull[0] - } - }; - - // Generate ordinal version of formatters: M -> Mo, D -> Do, etc. - var ordinalFormatters = ['M', 'D', 'DDD', 'd', 'Q', 'W']; - ordinalFormatters.forEach(function (formatterToken) { - formatters[formatterToken + 'o'] = function (date, formatters) { - return ordinal(formatters[formatterToken](date)) - }; - }); - - return { - formatters: formatters, - formattingTokensRegExp: build_formatting_tokens_reg_exp(formatters) - } - } - - function ordinal (number) { - var rem100 = number % 100; - if (rem100 > 20 || rem100 < 10) { - switch (rem100 % 10) { - case 1: - return number + 'st' - case 2: - return number + 'nd' - case 3: - return number + 'rd' - } - } - return number + 'th' - } - - var build_format_locale = buildFormatLocale; - - /** - * @category Locales - * @summary English locale. - */ - var en = { - distanceInWords: build_distance_in_words_locale(), - format: build_format_locale() - }; - - var MINUTES_IN_DAY$1 = 1440; - var MINUTES_IN_ALMOST_TWO_DAYS = 2520; - var MINUTES_IN_MONTH$1 = 43200; - var MINUTES_IN_TWO_MONTHS = 86400; - - /** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words. - * - * | Distance between dates | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance between dates | Result | - * |------------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWords( - * new Date(2014, 6, 2), - * new Date(2015, 0, 1) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00, including seconds? - * var result = distanceInWords( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWords( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> 'about 1 year ago' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWords( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ - function distanceInWords (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = Math.round(seconds / 60) - offset; - var months; - - // 0 up to 2 mins - if (minutes < 2) { - if (options.includeSeconds) { - if (seconds < 5) { - return localize('lessThanXSeconds', 5, localizeOptions) - } else if (seconds < 10) { - return localize('lessThanXSeconds', 10, localizeOptions) - } else if (seconds < 20) { - return localize('lessThanXSeconds', 20, localizeOptions) - } else if (seconds < 40) { - return localize('halfAMinute', null, localizeOptions) - } else if (seconds < 60) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', 1, localizeOptions) - } - } else { - if (minutes === 0) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', minutes, localizeOptions) - } - } - - // 2 mins up to 0.75 hrs - } else if (minutes < 45) { - return localize('xMinutes', minutes, localizeOptions) - - // 0.75 hrs up to 1.5 hrs - } else if (minutes < 90) { - return localize('aboutXHours', 1, localizeOptions) - - // 1.5 hrs up to 24 hrs - } else if (minutes < MINUTES_IN_DAY$1) { - var hours = Math.round(minutes / 60); - return localize('aboutXHours', hours, localizeOptions) - - // 1 day up to 1.75 days - } else if (minutes < MINUTES_IN_ALMOST_TWO_DAYS) { - return localize('xDays', 1, localizeOptions) - - // 1.75 days up to 30 days - } else if (minutes < MINUTES_IN_MONTH$1) { - var days = Math.round(minutes / MINUTES_IN_DAY$1); - return localize('xDays', days, localizeOptions) - - // 1 month up to 2 months - } else if (minutes < MINUTES_IN_TWO_MONTHS) { - months = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('aboutXMonths', months, localizeOptions) - } - - months = difference_in_months(dateRight, dateLeft); - - // 2 months up to 12 months - if (months < 12) { - var nearestMonth = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('xMonths', nearestMonth, localizeOptions) - - // 1 year up to max Date - } else { - var monthsSinceStartOfYear = months % 12; - var years = Math.floor(months / 12); - - // N years up to 1 years 3 months - if (monthsSinceStartOfYear < 3) { - return localize('aboutXYears', years, localizeOptions) - - // N years 3 months up to N years 9 months - } else if (monthsSinceStartOfYear < 9) { - return localize('overXYears', years, localizeOptions) - - // N years 9 months up to N year 12 months - } else { - return localize('almostXYears', years + 1, localizeOptions) - } - } - } - - var distance_in_words = distanceInWords; - - var MINUTES_IN_DAY = 1440; - var MINUTES_IN_MONTH = 43200; - var MINUTES_IN_YEAR = 525600; - - /** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words, using strict units. - * This is like `distanceInWords`, but does not use helpers like 'almost', 'over', - * 'less than' and the like. - * - * | Distance between dates | Result | - * |------------------------|---------------------| - * | 0 ... 59 secs | [0..59] seconds | - * | 1 ... 59 mins | [1..59] minutes | - * | 1 ... 23 hrs | [1..23] hours | - * | 1 ... 29 days | [1..29] days | - * | 1 ... 11 months | [1..11] months | - * | 1 ... N years | [1..N] years | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {'s'|'m'|'h'|'d'|'M'|'Y'} [options.unit] - if specified, will force a unit - * @param {'floor'|'ceil'|'round'} [options.partialMethod='floor'] - which way to round partial units - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWordsStrict( - * new Date(2014, 6, 2), - * new Date(2015, 0, 2) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * ) - * //=> '15 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> '1 year ago' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, in minutes? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {unit: 'm'} - * ) - * //=> '525600 minutes' - * - * @example - * // What is the distance from 1 January 2016 - * // to 28 January 2015, in months, rounded up? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 28), - * new Date(2015, 0, 1), - * {unit: 'M', partialMethod: 'ceil'} - * ) - * //=> '1 month' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsStrict( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> '1 jaro' - */ - function distanceInWordsStrict (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var unit; - var mathPartial = Math[options.partialMethod ? String(options.partialMethod) : 'floor']; - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = mathPartial(seconds / 60) - offset; - var hours, days, months, years; - - if (options.unit) { - unit = String(options.unit); - } else { - if (minutes < 1) { - unit = 's'; - } else if (minutes < 60) { - unit = 'm'; - } else if (minutes < MINUTES_IN_DAY) { - unit = 'h'; - } else if (minutes < MINUTES_IN_MONTH) { - unit = 'd'; - } else if (minutes < MINUTES_IN_YEAR) { - unit = 'M'; - } else { - unit = 'Y'; - } - } - - // 0 up to 60 seconds - if (unit === 's') { - return localize('xSeconds', seconds, localizeOptions) - - // 1 up to 60 mins - } else if (unit === 'm') { - return localize('xMinutes', minutes, localizeOptions) - - // 1 up to 24 hours - } else if (unit === 'h') { - hours = mathPartial(minutes / 60); - return localize('xHours', hours, localizeOptions) - - // 1 up to 30 days - } else if (unit === 'd') { - days = mathPartial(minutes / MINUTES_IN_DAY); - return localize('xDays', days, localizeOptions) - - // 1 up to 12 months - } else if (unit === 'M') { - months = mathPartial(minutes / MINUTES_IN_MONTH); - return localize('xMonths', months, localizeOptions) - - // 1 year up to max Date - } else if (unit === 'Y') { - years = mathPartial(minutes / MINUTES_IN_YEAR); - return localize('xYears', years, localizeOptions) - } - - throw new Error('Unknown unit: ' + unit) - } - - var distance_in_words_strict = distanceInWordsStrict; - - /** - * @category Common Helpers - * @summary Return the distance between the given date and now in words. - * - * @description - * Return the distance between the given date and now in words. - * - * | Distance to now | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance to now | Result | - * |---------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} date - the given date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result specifies if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // If today is 1 January 2015, what is the distance to 2 July 2014? - * var result = distanceInWordsToNow( - * new Date(2014, 6, 2) - * ) - * //=> '6 months' - * - * @example - * // If now is 1 January 2015 00:00:00, - * // what is the distance to 1 January 2015 00:00:15, including seconds? - * var result = distanceInWordsToNow( - * new Date(2015, 0, 1, 0, 0, 15), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 January 2016, with a suffix? - * var result = distanceInWordsToNow( - * new Date(2016, 0, 1), - * {addSuffix: true} - * ) - * //=> 'in about 1 year' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 August 2016 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsToNow( - * new Date(2016, 7, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ - function distanceInWordsToNow (dirtyDate, dirtyOptions) { - return distance_in_words(Date.now(), dirtyDate, dirtyOptions) - } - - var distance_in_words_to_now = distanceInWordsToNow; - - /** - * @category Day Helpers - * @summary Return the array of dates within the specified range. - * - * @description - * Return the array of dates within the specified range. - * - * @param {Date|String|Number} startDate - the first date - * @param {Date|String|Number} endDate - the last date - * @param {Number} [step=1] - the step between each day - * @returns {Date[]} the array with starts of days from the day of startDate to the day of endDate - * @throws {Error} startDate cannot be after endDate - * - * @example - * // Each day between 6 October 2014 and 10 October 2014: - * var result = eachDay( - * new Date(2014, 9, 6), - * new Date(2014, 9, 10) - * ) - * //=> [ - * // Mon Oct 06 2014 00:00:00, - * // Tue Oct 07 2014 00:00:00, - * // Wed Oct 08 2014 00:00:00, - * // Thu Oct 09 2014 00:00:00, - * // Fri Oct 10 2014 00:00:00 - * // ] - */ - function eachDay (dirtyStartDate, dirtyEndDate, dirtyStep) { - var startDate = parse_1(dirtyStartDate); - var endDate = parse_1(dirtyEndDate); - var step = dirtyStep !== undefined ? dirtyStep : 1; - - var endTime = endDate.getTime(); - - if (startDate.getTime() > endTime) { - throw new Error('The first date cannot be after the second date') - } - - var dates = []; - - var currentDate = startDate; - currentDate.setHours(0, 0, 0, 0); - - while (currentDate.getTime() <= endTime) { - dates.push(parse_1(currentDate)); - currentDate.setDate(currentDate.getDate() + step); - } - - return dates - } - - var each_day = eachDay; - - /** - * @category Day Helpers - * @summary Return the end of a day for the given date. - * - * @description - * Return the end of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a day - * - * @example - * // The end of a day for 2 September 2014 11:55:00: - * var result = endOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 23:59:59.999 - */ - function endOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_day = endOfDay; - - /** - * @category Hour Helpers - * @summary Return the end of an hour for the given date. - * - * @description - * Return the end of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an hour - * - * @example - * // The end of an hour for 2 September 2014 11:55:00: - * var result = endOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:59:59.999 - */ - function endOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(59, 59, 999); - return date - } - - var end_of_hour = endOfHour; - - /** - * @category Week Helpers - * @summary Return the end of a week for the given date. - * - * @description - * Return the end of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the end of a week - * - * @example - * // The end of a week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 23:59:59.999 - * - * @example - * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 23:59:59.999 - */ - function endOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setDate(date.getDate() + diff); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_week = endOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the end of an ISO week for the given date. - * - * @description - * Return the end of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week - * - * @example - * // The end of an ISO week for 2 September 2014 11:55:00: - * var result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 23:59:59.999 - */ - function endOfISOWeek (dirtyDate) { - return end_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var end_of_iso_week = endOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the end of an ISO week-numbering year for the given date. - * - * @description - * Return the end of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The end of an ISO week-numbering year for 2 July 2005: - * var result = endOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 23:59:59.999 - */ - function endOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuaryOfNextYear); - date.setMilliseconds(date.getMilliseconds() - 1); - return date - } - - var end_of_iso_year = endOfISOYear; - - /** - * @category Minute Helpers - * @summary Return the end of a minute for the given date. - * - * @description - * Return the end of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a minute - * - * @example - * // The end of a minute for 1 December 2014 22:15:45.400: - * var result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:59.999 - */ - function endOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(59, 999); - return date - } - - var end_of_minute = endOfMinute; - - /** - * @category Month Helpers - * @summary Return the end of a month for the given date. - * - * @description - * Return the end of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a month - * - * @example - * // The end of a month for 2 September 2014 11:55:00: - * var result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ - function endOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_month = endOfMonth; - - /** - * @category Quarter Helpers - * @summary Return the end of a year quarter for the given date. - * - * @description - * Return the end of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a quarter - * - * @example - * // The end of a quarter for 2 September 2014 11:55:00: - * var result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ - function endOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_quarter = endOfQuarter; - - /** - * @category Second Helpers - * @summary Return the end of a second for the given date. - * - * @description - * Return the end of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a second - * - * @example - * // The end of a second for 1 December 2014 22:15:45.400: - * var result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.999 - */ - function endOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(999); - return date - } - - var end_of_second = endOfSecond; - - /** - * @category Day Helpers - * @summary Return the end of today. - * - * @description - * Return the end of today. - * - * @returns {Date} the end of today - * - * @example - * // If today is 6 October 2014: - * var result = endOfToday() - * //=> Mon Oct 6 2014 23:59:59.999 - */ - function endOfToday () { - return end_of_day(new Date()) - } - - var end_of_today = endOfToday; - - /** - * @category Day Helpers - * @summary Return the end of tomorrow. - * - * @description - * Return the end of tomorrow. - * - * @returns {Date} the end of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = endOfTomorrow() - * //=> Tue Oct 7 2014 23:59:59.999 - */ - function endOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_tomorrow = endOfTomorrow; - - /** - * @category Year Helpers - * @summary Return the end of a year for the given date. - * - * @description - * Return the end of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a year - * - * @example - * // The end of a year for 2 September 2014 11:55:00: - * var result = endOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 23:59:59.999 - */ - function endOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_year = endOfYear; - - /** - * @category Day Helpers - * @summary Return the end of yesterday. - * - * @description - * Return the end of yesterday. - * - * @returns {Date} the end of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = endOfYesterday() - * //=> Sun Oct 5 2014 23:59:59.999 - */ - function endOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_yesterday = endOfYesterday; - - /** - * @category Year Helpers - * @summary Return the start of a year for the given date. - * - * @description - * Return the start of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a year - * - * @example - * // The start of a year for 2 September 2014 11:55:00: - * var result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Jan 01 2014 00:00:00 - */ - function startOfYear (dirtyDate) { - var cleanDate = parse_1(dirtyDate); - var date = new Date(0); - date.setFullYear(cleanDate.getFullYear(), 0, 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_year = startOfYear; - - /** - * @category Day Helpers - * @summary Get the day of the year of the given date. - * - * @description - * Get the day of the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of year - * - * @example - * // Which day of the year is 2 July 2014? - * var result = getDayOfYear(new Date(2014, 6, 2)) - * //=> 183 - */ - function getDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = difference_in_calendar_days(date, start_of_year(date)); - var dayOfYear = diff + 1; - return dayOfYear - } - - var get_day_of_year = getDayOfYear; - - var MILLISECONDS_IN_WEEK$1 = 604800000; - - /** - * @category ISO Week Helpers - * @summary Get the ISO week of the given date. - * - * @description - * Get the ISO week of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week - * - * @example - * // Which week of the ISO-week numbering year is 2 January 2005? - * var result = getISOWeek(new Date(2005, 0, 2)) - * //=> 53 - */ - function getISOWeek (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = start_of_iso_week(date).getTime() - start_of_iso_year(date).getTime(); - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1 - } - - var get_iso_week = getISOWeek; - - /** - * @category Common Helpers - * @summary Is the given date valid? - * - * @description - * Returns false if argument is Invalid Date and true otherwise. - * Invalid Date is a Date, whose time value is NaN. - * - * Time value of Date: http://es5.github.io/#x15.9.1.1 - * - * @param {Date} date - the date to check - * @returns {Boolean} the date is valid - * @throws {TypeError} argument must be an instance of Date - * - * @example - * // For the valid date: - * var result = isValid(new Date(2014, 1, 31)) - * //=> true - * - * @example - * // For the invalid date: - * var result = isValid(new Date('')) - * //=> false - */ - function isValid (dirtyDate) { - if (is_date(dirtyDate)) { - return !isNaN(dirtyDate) - } else { - throw new TypeError(toString.call(dirtyDate) + ' is not an instance of Date') - } - } - - var is_valid = isValid; - - /** - * @category Common Helpers - * @summary Format the date. - * - * @description - * Return the formatted date string in the given format. - * - * Accepted tokens: - * | Unit | Token | Result examples | - * |-------------------------|-------|----------------------------------| - * | Month | M | 1, 2, ..., 12 | - * | | Mo | 1st, 2nd, ..., 12th | - * | | MM | 01, 02, ..., 12 | - * | | MMM | Jan, Feb, ..., Dec | - * | | MMMM | January, February, ..., December | - * | Quarter | Q | 1, 2, 3, 4 | - * | | Qo | 1st, 2nd, 3rd, 4th | - * | Day of month | D | 1, 2, ..., 31 | - * | | Do | 1st, 2nd, ..., 31st | - * | | DD | 01, 02, ..., 31 | - * | Day of year | DDD | 1, 2, ..., 366 | - * | | DDDo | 1st, 2nd, ..., 366th | - * | | DDDD | 001, 002, ..., 366 | - * | Day of week | d | 0, 1, ..., 6 | - * | | do | 0th, 1st, ..., 6th | - * | | dd | Su, Mo, ..., Sa | - * | | ddd | Sun, Mon, ..., Sat | - * | | dddd | Sunday, Monday, ..., Saturday | - * | Day of ISO week | E | 1, 2, ..., 7 | - * | ISO week | W | 1, 2, ..., 53 | - * | | Wo | 1st, 2nd, ..., 53rd | - * | | WW | 01, 02, ..., 53 | - * | Year | YY | 00, 01, ..., 99 | - * | | YYYY | 1900, 1901, ..., 2099 | - * | ISO week-numbering year | GG | 00, 01, ..., 99 | - * | | GGGG | 1900, 1901, ..., 2099 | - * | AM/PM | A | AM, PM | - * | | a | am, pm | - * | | aa | a.m., p.m. | - * | Hour | H | 0, 1, ... 23 | - * | | HH | 00, 01, ... 23 | - * | | h | 1, 2, ..., 12 | - * | | hh | 01, 02, ..., 12 | - * | Minute | m | 0, 1, ..., 59 | - * | | mm | 00, 01, ..., 59 | - * | Second | s | 0, 1, ..., 59 | - * | | ss | 00, 01, ..., 59 | - * | 1/10 of second | S | 0, 1, ..., 9 | - * | 1/100 of second | SS | 00, 01, ..., 99 | - * | Millisecond | SSS | 000, 001, ..., 999 | - * | Timezone | Z | -01:00, +00:00, ... +12:00 | - * | | ZZ | -0100, +0000, ..., +1200 | - * | Seconds timestamp | X | 512969520 | - * | Milliseconds timestamp | x | 512969520900 | - * - * The characters wrapped in square brackets are escaped. - * - * The result may vary by locale. - * - * @param {Date|String|Number} date - the original date - * @param {String} [format='YYYY-MM-DDTHH:mm:ss.SSSZ'] - the string of tokens - * @param {Object} [options] - the object with options - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the formatted date string - * - * @example - * // Represent 11 February 2014 in middle-endian format: - * var result = format( - * new Date(2014, 1, 11), - * 'MM/DD/YYYY' - * ) - * //=> '02/11/2014' - * - * @example - * // Represent 2 July 2014 in Esperanto: - * var eoLocale = require('date-fns/locale/eo') - * var result = format( - * new Date(2014, 6, 2), - * 'Do [de] MMMM YYYY', - * {locale: eoLocale} - * ) - * //=> '2-a de julio 2014' - */ - function format (dirtyDate, dirtyFormatStr, dirtyOptions) { - var formatStr = dirtyFormatStr ? String(dirtyFormatStr) : 'YYYY-MM-DDTHH:mm:ss.SSSZ'; - var options = dirtyOptions || {}; - - var locale = options.locale; - var localeFormatters = en.format.formatters; - var formattingTokensRegExp = en.format.formattingTokensRegExp; - if (locale && locale.format && locale.format.formatters) { - localeFormatters = locale.format.formatters; - - if (locale.format.formattingTokensRegExp) { - formattingTokensRegExp = locale.format.formattingTokensRegExp; - } - } - - var date = parse_1(dirtyDate); - - if (!is_valid(date)) { - return 'Invalid Date' - } - - var formatFn = buildFormatFn(formatStr, localeFormatters, formattingTokensRegExp); - - return formatFn(date) - } - - var formatters = { - // Month: 1, 2, ..., 12 - 'M': function (date) { - return date.getMonth() + 1 - }, - - // Month: 01, 02, ..., 12 - 'MM': function (date) { - return addLeadingZeros(date.getMonth() + 1, 2) - }, - - // Quarter: 1, 2, 3, 4 - 'Q': function (date) { - return Math.ceil((date.getMonth() + 1) / 3) - }, - - // Day of month: 1, 2, ..., 31 - 'D': function (date) { - return date.getDate() - }, - - // Day of month: 01, 02, ..., 31 - 'DD': function (date) { - return addLeadingZeros(date.getDate(), 2) - }, - - // Day of year: 1, 2, ..., 366 - 'DDD': function (date) { - return get_day_of_year(date) - }, - - // Day of year: 001, 002, ..., 366 - 'DDDD': function (date) { - return addLeadingZeros(get_day_of_year(date), 3) - }, - - // Day of week: 0, 1, ..., 6 - 'd': function (date) { - return date.getDay() - }, - - // Day of ISO week: 1, 2, ..., 7 - 'E': function (date) { - return date.getDay() || 7 - }, - - // ISO week: 1, 2, ..., 53 - 'W': function (date) { - return get_iso_week(date) - }, - - // ISO week: 01, 02, ..., 53 - 'WW': function (date) { - return addLeadingZeros(get_iso_week(date), 2) - }, - - // Year: 00, 01, ..., 99 - 'YY': function (date) { - return addLeadingZeros(date.getFullYear(), 4).substr(2) - }, - - // Year: 1900, 1901, ..., 2099 - 'YYYY': function (date) { - return addLeadingZeros(date.getFullYear(), 4) - }, - - // ISO week-numbering year: 00, 01, ..., 99 - 'GG': function (date) { - return String(get_iso_year(date)).substr(2) - }, - - // ISO week-numbering year: 1900, 1901, ..., 2099 - 'GGGG': function (date) { - return get_iso_year(date) - }, - - // Hour: 0, 1, ... 23 - 'H': function (date) { - return date.getHours() - }, - - // Hour: 00, 01, ..., 23 - 'HH': function (date) { - return addLeadingZeros(date.getHours(), 2) - }, - - // Hour: 1, 2, ..., 12 - 'h': function (date) { - var hours = date.getHours(); - if (hours === 0) { - return 12 - } else if (hours > 12) { - return hours % 12 - } else { - return hours - } - }, - - // Hour: 01, 02, ..., 12 - 'hh': function (date) { - return addLeadingZeros(formatters['h'](date), 2) - }, - - // Minute: 0, 1, ..., 59 - 'm': function (date) { - return date.getMinutes() - }, - - // Minute: 00, 01, ..., 59 - 'mm': function (date) { - return addLeadingZeros(date.getMinutes(), 2) - }, - - // Second: 0, 1, ..., 59 - 's': function (date) { - return date.getSeconds() - }, - - // Second: 00, 01, ..., 59 - 'ss': function (date) { - return addLeadingZeros(date.getSeconds(), 2) - }, - - // 1/10 of second: 0, 1, ..., 9 - 'S': function (date) { - return Math.floor(date.getMilliseconds() / 100) - }, - - // 1/100 of second: 00, 01, ..., 99 - 'SS': function (date) { - return addLeadingZeros(Math.floor(date.getMilliseconds() / 10), 2) - }, - - // Millisecond: 000, 001, ..., 999 - 'SSS': function (date) { - return addLeadingZeros(date.getMilliseconds(), 3) - }, - - // Timezone: -01:00, +00:00, ... +12:00 - 'Z': function (date) { - return formatTimezone(date.getTimezoneOffset(), ':') - }, - - // Timezone: -0100, +0000, ... +1200 - 'ZZ': function (date) { - return formatTimezone(date.getTimezoneOffset()) - }, - - // Seconds timestamp: 512969520 - 'X': function (date) { - return Math.floor(date.getTime() / 1000) - }, - - // Milliseconds timestamp: 512969520900 - 'x': function (date) { - return date.getTime() - } - }; - - function buildFormatFn (formatStr, localeFormatters, formattingTokensRegExp) { - var array = formatStr.match(formattingTokensRegExp); - var length = array.length; - - var i; - var formatter; - for (i = 0; i < length; i++) { - formatter = localeFormatters[array[i]] || formatters[array[i]]; - if (formatter) { - array[i] = formatter; - } else { - array[i] = removeFormattingTokens(array[i]); - } - } - - return function (date) { - var output = ''; - for (var i = 0; i < length; i++) { - if (array[i] instanceof Function) { - output += array[i](date, formatters); - } else { - output += array[i]; - } - } - return output - } - } - - function removeFormattingTokens (input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|]$/g, '') - } - return input.replace(/\\/g, '') - } - - function formatTimezone (offset, delimeter) { - delimeter = delimeter || ''; - var sign = offset > 0 ? '-' : '+'; - var absOffset = Math.abs(offset); - var hours = Math.floor(absOffset / 60); - var minutes = absOffset % 60; - return sign + addLeadingZeros(hours, 2) + delimeter + addLeadingZeros(minutes, 2) - } - - function addLeadingZeros (number, targetLength) { - var output = Math.abs(number).toString(); - while (output.length < targetLength) { - output = '0' + output; - } - return output - } - - var format_1 = format; - - /** - * @category Day Helpers - * @summary Get the day of the month of the given date. - * - * @description - * Get the day of the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of month - * - * @example - * // Which day of the month is 29 February 2012? - * var result = getDate(new Date(2012, 1, 29)) - * //=> 29 - */ - function getDate (dirtyDate) { - var date = parse_1(dirtyDate); - var dayOfMonth = date.getDate(); - return dayOfMonth - } - - var get_date = getDate; - - /** - * @category Weekday Helpers - * @summary Get the day of the week of the given date. - * - * @description - * Get the day of the week of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of week - * - * @example - * // Which day of the week is 29 February 2012? - * var result = getDay(new Date(2012, 1, 29)) - * //=> 3 - */ - function getDay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day - } - - var get_day = getDay; - - /** - * @category Year Helpers - * @summary Is the given date in the leap year? - * - * @description - * Is the given date in the leap year? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the leap year - * - * @example - * // Is 1 September 2012 in the leap year? - * var result = isLeapYear(new Date(2012, 8, 1)) - * //=> true - */ - function isLeapYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0 - } - - var is_leap_year = isLeapYear; - - /** - * @category Year Helpers - * @summary Get the number of days in a year of the given date. - * - * @description - * Get the number of days in a year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a year - * - * @example - * // How many days are in 2012? - * var result = getDaysInYear(new Date(2012, 0, 1)) - * //=> 366 - */ - function getDaysInYear (dirtyDate) { - return is_leap_year(dirtyDate) ? 366 : 365 - } - - var get_days_in_year = getDaysInYear; - - /** - * @category Hour Helpers - * @summary Get the hours of the given date. - * - * @description - * Get the hours of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the hours - * - * @example - * // Get the hours of 29 February 2012 11:45:00: - * var result = getHours(new Date(2012, 1, 29, 11, 45)) - * //=> 11 - */ - function getHours (dirtyDate) { - var date = parse_1(dirtyDate); - var hours = date.getHours(); - return hours - } - - var get_hours = getHours; - - /** - * @category Weekday Helpers - * @summary Get the day of the ISO week of the given date. - * - * @description - * Get the day of the ISO week of the given date, - * which is 7 for Sunday, 1 for Monday etc. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of ISO week - * - * @example - * // Which day of the ISO week is 26 February 2012? - * var result = getISODay(new Date(2012, 1, 26)) - * //=> 7 - */ - function getISODay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - - if (day === 0) { - day = 7; - } - - return day - } - - var get_iso_day = getISODay; - - var MILLISECONDS_IN_WEEK = 604800000; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of weeks in an ISO week-numbering year of the given date. - * - * @description - * Get the number of weeks in an ISO week-numbering year of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of ISO weeks in a year - * - * @example - * // How many weeks are in ISO week-numbering year 2015? - * var result = getISOWeeksInYear(new Date(2015, 1, 11)) - * //=> 53 - */ - function getISOWeeksInYear (dirtyDate) { - var thisYear = start_of_iso_year(dirtyDate); - var nextYear = start_of_iso_year(add_weeks(thisYear, 60)); - var diff = nextYear.valueOf() - thisYear.valueOf(); - // Round the number of weeks to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK) - } - - var get_iso_weeks_in_year = getISOWeeksInYear; - - /** - * @category Millisecond Helpers - * @summary Get the milliseconds of the given date. - * - * @description - * Get the milliseconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the milliseconds - * - * @example - * // Get the milliseconds of 29 February 2012 11:45:05.123: - * var result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 123 - */ - function getMilliseconds (dirtyDate) { - var date = parse_1(dirtyDate); - var milliseconds = date.getMilliseconds(); - return milliseconds - } - - var get_milliseconds = getMilliseconds; - - /** - * @category Minute Helpers - * @summary Get the minutes of the given date. - * - * @description - * Get the minutes of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the minutes - * - * @example - * // Get the minutes of 29 February 2012 11:45:05: - * var result = getMinutes(new Date(2012, 1, 29, 11, 45, 5)) - * //=> 45 - */ - function getMinutes (dirtyDate) { - var date = parse_1(dirtyDate); - var minutes = date.getMinutes(); - return minutes - } - - var get_minutes = getMinutes; - - /** - * @category Month Helpers - * @summary Get the month of the given date. - * - * @description - * Get the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the month - * - * @example - * // Which month is 29 February 2012? - * var result = getMonth(new Date(2012, 1, 29)) - * //=> 1 - */ - function getMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - return month - } - - var get_month = getMonth; - - var MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000; - - /** - * @category Range Helpers - * @summary Get the number of days that overlap in two date ranges - * - * @description - * Get the number of days that overlap in two date ranges - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Number} the number of days that overlap in two date ranges - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges adds 1 for each started overlapping day: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> 3 - * - * @example - * // For non-overlapping date ranges returns 0: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> 0 - */ - function getOverlappingDaysInRanges (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - var isOverlapping = initialStartTime < comparedEndTime && comparedStartTime < initialEndTime; - - if (!isOverlapping) { - return 0 - } - - var overlapStartDate = comparedStartTime < initialStartTime - ? initialStartTime - : comparedStartTime; - - var overlapEndDate = comparedEndTime > initialEndTime - ? initialEndTime - : comparedEndTime; - - var differenceInMs = overlapEndDate - overlapStartDate; - - return Math.ceil(differenceInMs / MILLISECONDS_IN_DAY) - } - - var get_overlapping_days_in_ranges = getOverlappingDaysInRanges; - - /** - * @category Second Helpers - * @summary Get the seconds of the given date. - * - * @description - * Get the seconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the seconds - * - * @example - * // Get the seconds of 29 February 2012 11:45:05.123: - * var result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 5 - */ - function getSeconds (dirtyDate) { - var date = parse_1(dirtyDate); - var seconds = date.getSeconds(); - return seconds - } - - var get_seconds = getSeconds; - - /** - * @category Timestamp Helpers - * @summary Get the milliseconds timestamp of the given date. - * - * @description - * Get the milliseconds timestamp of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the timestamp - * - * @example - * // Get the timestamp of 29 February 2012 11:45:05.123: - * var result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 1330515905123 - */ - function getTime (dirtyDate) { - var date = parse_1(dirtyDate); - var timestamp = date.getTime(); - return timestamp - } - - var get_time = getTime; - - /** - * @category Year Helpers - * @summary Get the year of the given date. - * - * @description - * Get the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the year - * - * @example - * // Which year is 2 July 2014? - * var result = getYear(new Date(2014, 6, 2)) - * //=> 2014 - */ - function getYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year - } - - var get_year = getYear; - - /** - * @category Common Helpers - * @summary Is the first date after the second one? - * - * @description - * Is the first date after the second one? - * - * @param {Date|String|Number} date - the date that should be after the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is after the second date - * - * @example - * // Is 10 July 1989 after 11 February 1987? - * var result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> true - */ - function isAfter (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() > dateToCompare.getTime() - } - - var is_after = isAfter; - - /** - * @category Common Helpers - * @summary Is the first date before the second one? - * - * @description - * Is the first date before the second one? - * - * @param {Date|String|Number} date - the date that should be before the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is before the second date - * - * @example - * // Is 10 July 1989 before 11 February 1987? - * var result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> false - */ - function isBefore (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() < dateToCompare.getTime() - } - - var is_before = isBefore; - - /** - * @category Common Helpers - * @summary Are the given dates equal? - * - * @description - * Are the given dates equal? - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Boolean} the dates are equal - * - * @example - * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal? - * var result = isEqual( - * new Date(2014, 6, 2, 6, 30, 45, 0) - * new Date(2014, 6, 2, 6, 30, 45, 500) - * ) - * //=> false - */ - function isEqual (dirtyLeftDate, dirtyRightDate) { - var dateLeft = parse_1(dirtyLeftDate); - var dateRight = parse_1(dirtyRightDate); - return dateLeft.getTime() === dateRight.getTime() - } - - var is_equal = isEqual; - - /** - * @category Month Helpers - * @summary Is the given date the first day of a month? - * - * @description - * Is the given date the first day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the first day of a month - * - * @example - * // Is 1 September 2014 the first day of a month? - * var result = isFirstDayOfMonth(new Date(2014, 8, 1)) - * //=> true - */ - function isFirstDayOfMonth (dirtyDate) { - return parse_1(dirtyDate).getDate() === 1 - } - - var is_first_day_of_month = isFirstDayOfMonth; - - /** - * @category Weekday Helpers - * @summary Is the given date Friday? - * - * @description - * Is the given date Friday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Friday - * - * @example - * // Is 26 September 2014 Friday? - * var result = isFriday(new Date(2014, 8, 26)) - * //=> true - */ - function isFriday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 5 - } - - var is_friday = isFriday; - - /** - * @category Common Helpers - * @summary Is the given date in the future? - * - * @description - * Is the given date in the future? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the future - * - * @example - * // If today is 6 October 2014, is 31 December 2014 in the future? - * var result = isFuture(new Date(2014, 11, 31)) - * //=> true - */ - function isFuture (dirtyDate) { - return parse_1(dirtyDate).getTime() > new Date().getTime() - } - - var is_future = isFuture; - - /** - * @category Month Helpers - * @summary Is the given date the last day of a month? - * - * @description - * Is the given date the last day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the last day of a month - * - * @example - * // Is 28 February 2014 the last day of a month? - * var result = isLastDayOfMonth(new Date(2014, 1, 28)) - * //=> true - */ - function isLastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - return end_of_day(date).getTime() === end_of_month(date).getTime() - } - - var is_last_day_of_month = isLastDayOfMonth; - - /** - * @category Weekday Helpers - * @summary Is the given date Monday? - * - * @description - * Is the given date Monday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Monday - * - * @example - * // Is 22 September 2014 Monday? - * var result = isMonday(new Date(2014, 8, 22)) - * //=> true - */ - function isMonday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 1 - } - - var is_monday = isMonday; - - /** - * @category Common Helpers - * @summary Is the given date in the past? - * - * @description - * Is the given date in the past? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the past - * - * @example - * // If today is 6 October 2014, is 2 July 2014 in the past? - * var result = isPast(new Date(2014, 6, 2)) - * //=> true - */ - function isPast (dirtyDate) { - return parse_1(dirtyDate).getTime() < new Date().getTime() - } - - var is_past = isPast; - - /** - * @category Day Helpers - * @summary Are the given dates in the same day? - * - * @description - * Are the given dates in the same day? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same day - * - * @example - * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? - * var result = isSameDay( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 18, 0) - * ) - * //=> true - */ - function isSameDay (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfDay = start_of_day(dirtyDateLeft); - var dateRightStartOfDay = start_of_day(dirtyDateRight); - - return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime() - } - - var is_same_day = isSameDay; - - /** - * @category Hour Helpers - * @summary Return the start of an hour for the given date. - * - * @description - * Return the start of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an hour - * - * @example - * // The start of an hour for 2 September 2014 11:55:00: - * var result = startOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:00:00 - */ - function startOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(0, 0, 0); - return date - } - - var start_of_hour = startOfHour; - - /** - * @category Hour Helpers - * @summary Are the given dates in the same hour? - * - * @description - * Are the given dates in the same hour? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same hour - * - * @example - * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour? - * var result = isSameHour( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 6, 30) - * ) - * //=> true - */ - function isSameHour (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfHour = start_of_hour(dirtyDateLeft); - var dateRightStartOfHour = start_of_hour(dirtyDateRight); - - return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime() - } - - var is_same_hour = isSameHour; - - /** - * @category Week Helpers - * @summary Are the given dates in the same week? - * - * @description - * Are the given dates in the same week? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the dates are in the same week - * - * @example - * // Are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4) - * ) - * //=> true - * - * @example - * // If week starts with Monday, - * // are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4), - * {weekStartsOn: 1} - * ) - * //=> false - */ - function isSameWeek (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var dateLeftStartOfWeek = start_of_week(dirtyDateLeft, dirtyOptions); - var dateRightStartOfWeek = start_of_week(dirtyDateRight, dirtyOptions); - - return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime() - } - - var is_same_week = isSameWeek; - - /** - * @category ISO Week Helpers - * @summary Are the given dates in the same ISO week? - * - * @description - * Are the given dates in the same ISO week? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week - * - * @example - * // Are 1 September 2014 and 7 September 2014 in the same ISO week? - * var result = isSameISOWeek( - * new Date(2014, 8, 1), - * new Date(2014, 8, 7) - * ) - * //=> true - */ - function isSameISOWeek (dirtyDateLeft, dirtyDateRight) { - return is_same_week(dirtyDateLeft, dirtyDateRight, {weekStartsOn: 1}) - } - - var is_same_iso_week = isSameISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Are the given dates in the same ISO week-numbering year? - * - * @description - * Are the given dates in the same ISO week-numbering year? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week-numbering year - * - * @example - * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? - * var result = isSameISOYear( - * new Date(2003, 11, 29), - * new Date(2005, 0, 2) - * ) - * //=> true - */ - function isSameISOYear (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfYear = start_of_iso_year(dirtyDateLeft); - var dateRightStartOfYear = start_of_iso_year(dirtyDateRight); - - return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime() - } - - var is_same_iso_year = isSameISOYear; - - /** - * @category Minute Helpers - * @summary Return the start of a minute for the given date. - * - * @description - * Return the start of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a minute - * - * @example - * // The start of a minute for 1 December 2014 22:15:45.400: - * var result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:00 - */ - function startOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(0, 0); - return date - } - - var start_of_minute = startOfMinute; - - /** - * @category Minute Helpers - * @summary Are the given dates in the same minute? - * - * @description - * Are the given dates in the same minute? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same minute - * - * @example - * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 - * // in the same minute? - * var result = isSameMinute( - * new Date(2014, 8, 4, 6, 30), - * new Date(2014, 8, 4, 6, 30, 15) - * ) - * //=> true - */ - function isSameMinute (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfMinute = start_of_minute(dirtyDateLeft); - var dateRightStartOfMinute = start_of_minute(dirtyDateRight); - - return dateLeftStartOfMinute.getTime() === dateRightStartOfMinute.getTime() - } - - var is_same_minute = isSameMinute; - - /** - * @category Month Helpers - * @summary Are the given dates in the same month? - * - * @description - * Are the given dates in the same month? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same month - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same month? - * var result = isSameMonth( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ - function isSameMonth (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() && - dateLeft.getMonth() === dateRight.getMonth() - } - - var is_same_month = isSameMonth; - - /** - * @category Quarter Helpers - * @summary Return the start of a year quarter for the given date. - * - * @description - * Return the start of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a quarter - * - * @example - * // The start of a quarter for 2 September 2014 11:55:00: - * var result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Jul 01 2014 00:00:00 - */ - function startOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3; - date.setMonth(month, 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_quarter = startOfQuarter; - - /** - * @category Quarter Helpers - * @summary Are the given dates in the same year quarter? - * - * @description - * Are the given dates in the same year quarter? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same quarter - * - * @example - * // Are 1 January 2014 and 8 March 2014 in the same quarter? - * var result = isSameQuarter( - * new Date(2014, 0, 1), - * new Date(2014, 2, 8) - * ) - * //=> true - */ - function isSameQuarter (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfQuarter = start_of_quarter(dirtyDateLeft); - var dateRightStartOfQuarter = start_of_quarter(dirtyDateRight); - - return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime() - } - - var is_same_quarter = isSameQuarter; - - /** - * @category Second Helpers - * @summary Return the start of a second for the given date. - * - * @description - * Return the start of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a second - * - * @example - * // The start of a second for 1 December 2014 22:15:45.400: - * var result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.000 - */ - function startOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(0); - return date - } - - var start_of_second = startOfSecond; - - /** - * @category Second Helpers - * @summary Are the given dates in the same second? - * - * @description - * Are the given dates in the same second? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same second - * - * @example - * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 - * // in the same second? - * var result = isSameSecond( - * new Date(2014, 8, 4, 6, 30, 15), - * new Date(2014, 8, 4, 6, 30, 15, 500) - * ) - * //=> true - */ - function isSameSecond (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfSecond = start_of_second(dirtyDateLeft); - var dateRightStartOfSecond = start_of_second(dirtyDateRight); - - return dateLeftStartOfSecond.getTime() === dateRightStartOfSecond.getTime() - } - - var is_same_second = isSameSecond; - - /** - * @category Year Helpers - * @summary Are the given dates in the same year? - * - * @description - * Are the given dates in the same year? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same year - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same year? - * var result = isSameYear( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ - function isSameYear (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() - } - - var is_same_year = isSameYear; - - /** - * @category Weekday Helpers - * @summary Is the given date Saturday? - * - * @description - * Is the given date Saturday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Saturday - * - * @example - * // Is 27 September 2014 Saturday? - * var result = isSaturday(new Date(2014, 8, 27)) - * //=> true - */ - function isSaturday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 6 - } - - var is_saturday = isSaturday; - - /** - * @category Weekday Helpers - * @summary Is the given date Sunday? - * - * @description - * Is the given date Sunday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Sunday - * - * @example - * // Is 21 September 2014 Sunday? - * var result = isSunday(new Date(2014, 8, 21)) - * //=> true - */ - function isSunday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 0 - } - - var is_sunday = isSunday; - - /** - * @category Hour Helpers - * @summary Is the given date in the same hour as the current date? - * - * @description - * Is the given date in the same hour as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this hour - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:00:00 in this hour? - * var result = isThisHour(new Date(2014, 8, 25, 18)) - * //=> true - */ - function isThisHour (dirtyDate) { - return is_same_hour(new Date(), dirtyDate) - } - - var is_this_hour = isThisHour; - - /** - * @category ISO Week Helpers - * @summary Is the given date in the same ISO week as the current date? - * - * @description - * Is the given date in the same ISO week as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week - * - * @example - * // If today is 25 September 2014, is 22 September 2014 in this ISO week? - * var result = isThisISOWeek(new Date(2014, 8, 22)) - * //=> true - */ - function isThisISOWeek (dirtyDate) { - return is_same_iso_week(new Date(), dirtyDate) - } - - var is_this_iso_week = isThisISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Is the given date in the same ISO week-numbering year as the current date? - * - * @description - * Is the given date in the same ISO week-numbering year as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week-numbering year - * - * @example - * // If today is 25 September 2014, - * // is 30 December 2013 in this ISO week-numbering year? - * var result = isThisISOYear(new Date(2013, 11, 30)) - * //=> true - */ - function isThisISOYear (dirtyDate) { - return is_same_iso_year(new Date(), dirtyDate) - } - - var is_this_iso_year = isThisISOYear; - - /** - * @category Minute Helpers - * @summary Is the given date in the same minute as the current date? - * - * @description - * Is the given date in the same minute as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this minute - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:00 in this minute? - * var result = isThisMinute(new Date(2014, 8, 25, 18, 30)) - * //=> true - */ - function isThisMinute (dirtyDate) { - return is_same_minute(new Date(), dirtyDate) - } - - var is_this_minute = isThisMinute; - - /** - * @category Month Helpers - * @summary Is the given date in the same month as the current date? - * - * @description - * Is the given date in the same month as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this month - * - * @example - * // If today is 25 September 2014, is 15 September 2014 in this month? - * var result = isThisMonth(new Date(2014, 8, 15)) - * //=> true - */ - function isThisMonth (dirtyDate) { - return is_same_month(new Date(), dirtyDate) - } - - var is_this_month = isThisMonth; - - /** - * @category Quarter Helpers - * @summary Is the given date in the same quarter as the current date? - * - * @description - * Is the given date in the same quarter as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this quarter - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this quarter? - * var result = isThisQuarter(new Date(2014, 6, 2)) - * //=> true - */ - function isThisQuarter (dirtyDate) { - return is_same_quarter(new Date(), dirtyDate) - } - - var is_this_quarter = isThisQuarter; - - /** - * @category Second Helpers - * @summary Is the given date in the same second as the current date? - * - * @description - * Is the given date in the same second as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this second - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:15.000 in this second? - * var result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15)) - * //=> true - */ - function isThisSecond (dirtyDate) { - return is_same_second(new Date(), dirtyDate) - } - - var is_this_second = isThisSecond; - - /** - * @category Week Helpers - * @summary Is the given date in the same week as the current date? - * - * @description - * Is the given date in the same week as the current date? - * - * @param {Date|String|Number} date - the date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the date is in this week - * - * @example - * // If today is 25 September 2014, is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21)) - * //=> true - * - * @example - * // If today is 25 September 2014 and week starts with Monday - * // is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21), {weekStartsOn: 1}) - * //=> false - */ - function isThisWeek (dirtyDate, dirtyOptions) { - return is_same_week(new Date(), dirtyDate, dirtyOptions) - } - - var is_this_week = isThisWeek; - - /** - * @category Year Helpers - * @summary Is the given date in the same year as the current date? - * - * @description - * Is the given date in the same year as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this year - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this year? - * var result = isThisYear(new Date(2014, 6, 2)) - * //=> true - */ - function isThisYear (dirtyDate) { - return is_same_year(new Date(), dirtyDate) - } - - var is_this_year = isThisYear; - - /** - * @category Weekday Helpers - * @summary Is the given date Thursday? - * - * @description - * Is the given date Thursday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Thursday - * - * @example - * // Is 25 September 2014 Thursday? - * var result = isThursday(new Date(2014, 8, 25)) - * //=> true - */ - function isThursday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 4 - } - - var is_thursday = isThursday; - - /** - * @category Day Helpers - * @summary Is the given date today? - * - * @description - * Is the given date today? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is today - * - * @example - * // If today is 6 October 2014, is 6 October 14:00:00 today? - * var result = isToday(new Date(2014, 9, 6, 14, 0)) - * //=> true - */ - function isToday (dirtyDate) { - return start_of_day(dirtyDate).getTime() === start_of_day(new Date()).getTime() - } - - var is_today = isToday; - - /** - * @category Day Helpers - * @summary Is the given date tomorrow? - * - * @description - * Is the given date tomorrow? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is tomorrow - * - * @example - * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow? - * var result = isTomorrow(new Date(2014, 9, 7, 14, 0)) - * //=> true - */ - function isTomorrow (dirtyDate) { - var tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 1); - return start_of_day(dirtyDate).getTime() === start_of_day(tomorrow).getTime() - } - - var is_tomorrow = isTomorrow; - - /** - * @category Weekday Helpers - * @summary Is the given date Tuesday? - * - * @description - * Is the given date Tuesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Tuesday - * - * @example - * // Is 23 September 2014 Tuesday? - * var result = isTuesday(new Date(2014, 8, 23)) - * //=> true - */ - function isTuesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 2 - } - - var is_tuesday = isTuesday; - - /** - * @category Weekday Helpers - * @summary Is the given date Wednesday? - * - * @description - * Is the given date Wednesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Wednesday - * - * @example - * // Is 24 September 2014 Wednesday? - * var result = isWednesday(new Date(2014, 8, 24)) - * //=> true - */ - function isWednesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 3 - } - - var is_wednesday = isWednesday; - - /** - * @category Weekday Helpers - * @summary Does the given date fall on a weekend? - * - * @description - * Does the given date fall on a weekend? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date falls on a weekend - * - * @example - * // Does 5 October 2014 fall on a weekend? - * var result = isWeekend(new Date(2014, 9, 5)) - * //=> true - */ - function isWeekend (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day === 0 || day === 6 - } - - var is_weekend = isWeekend; - - /** - * @category Range Helpers - * @summary Is the given date within the range? - * - * @description - * Is the given date within the range? - * - * @param {Date|String|Number} date - the date to check - * @param {Date|String|Number} startDate - the start of range - * @param {Date|String|Number} endDate - the end of range - * @returns {Boolean} the date is within the range - * @throws {Error} startDate cannot be after endDate - * - * @example - * // For the date within the range: - * isWithinRange( - * new Date(2014, 0, 3), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> true - * - * @example - * // For the date outside of the range: - * isWithinRange( - * new Date(2014, 0, 10), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> false - */ - function isWithinRange (dirtyDate, dirtyStartDate, dirtyEndDate) { - var time = parse_1(dirtyDate).getTime(); - var startTime = parse_1(dirtyStartDate).getTime(); - var endTime = parse_1(dirtyEndDate).getTime(); - - if (startTime > endTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return time >= startTime && time <= endTime - } - - var is_within_range = isWithinRange; - - /** - * @category Day Helpers - * @summary Is the given date yesterday? - * - * @description - * Is the given date yesterday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is yesterday - * - * @example - * // If today is 6 October 2014, is 5 October 14:00:00 yesterday? - * var result = isYesterday(new Date(2014, 9, 5, 14, 0)) - * //=> true - */ - function isYesterday (dirtyDate) { - var yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - return start_of_day(dirtyDate).getTime() === start_of_day(yesterday).getTime() - } - - var is_yesterday = isYesterday; - - /** - * @category Week Helpers - * @summary Return the last day of a week for the given date. - * - * @description - * Return the last day of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the last day of a week - * - * @example - * // The last day of a week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ - function lastDayOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setHours(0, 0, 0, 0); - date.setDate(date.getDate() + diff); - return date - } - - var last_day_of_week = lastDayOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the last day of an ISO week for the given date. - * - * @description - * Return the last day of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of an ISO week - * - * @example - * // The last day of an ISO week for 2 September 2014 11:55:00: - * var result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 00:00:00 - */ - function lastDayOfISOWeek (dirtyDate) { - return last_day_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var last_day_of_iso_week = lastDayOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the last day of an ISO week-numbering year for the given date. - * - * @description - * Return the last day of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The last day of an ISO week-numbering year for 2 July 2005: - * var result = lastDayOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 00:00:00 - */ - function lastDayOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year + 1, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - date.setDate(date.getDate() - 1); - return date - } - - var last_day_of_iso_year = lastDayOfISOYear; - - /** - * @category Month Helpers - * @summary Return the last day of a month for the given date. - * - * @description - * Return the last day of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a month - * - * @example - * // The last day of a month for 2 September 2014 11:55:00: - * var result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ - function lastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_month = lastDayOfMonth; - - /** - * @category Quarter Helpers - * @summary Return the last day of a year quarter for the given date. - * - * @description - * Return the last day of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a quarter - * - * @example - * // The last day of a quarter for 2 September 2014 11:55:00: - * var result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ - function lastDayOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_quarter = lastDayOfQuarter; - - /** - * @category Year Helpers - * @summary Return the last day of a year for the given date. - * - * @description - * Return the last day of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a year - * - * @example - * // The last day of a year for 2 September 2014 11:55:00: - * var result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 00:00:00 - */ - function lastDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_year = lastDayOfYear; - - /** - * @category Common Helpers - * @summary Return the latest of the given dates. - * - * @description - * Return the latest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the latest of the dates - * - * @example - * // Which of these dates is the latest? - * var result = max( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Sun Jul 02 1995 00:00:00 - */ - function max () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var latestTimestamp = Math.max.apply(null, dates); - return new Date(latestTimestamp) - } - - var max_1 = max; - - /** - * @category Common Helpers - * @summary Return the earliest of the given dates. - * - * @description - * Return the earliest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the earliest of the dates - * - * @example - * // Which of these dates is the earliest? - * var result = min( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Wed Feb 11 1987 00:00:00 - */ - function min () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var earliestTimestamp = Math.min.apply(null, dates); - return new Date(earliestTimestamp) - } - - var min_1 = min; - - /** - * @category Day Helpers - * @summary Set the day of the month to the given date. - * - * @description - * Set the day of the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfMonth - the day of the month of the new date - * @returns {Date} the new date with the day of the month setted - * - * @example - * // Set the 30th day of the month to 1 September 2014: - * var result = setDate(new Date(2014, 8, 1), 30) - * //=> Tue Sep 30 2014 00:00:00 - */ - function setDate (dirtyDate, dirtyDayOfMonth) { - var date = parse_1(dirtyDate); - var dayOfMonth = Number(dirtyDayOfMonth); - date.setDate(dayOfMonth); - return date - } - - var set_date = setDate; - - /** - * @category Weekday Helpers - * @summary Set the day of the week to the given date. - * - * @description - * Set the day of the week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the week of the new date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the new date with the day of the week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If week starts with Monday, set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0, {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ - function setDay (dirtyDate, dirtyDay, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = date.getDay(); - - var remainder = day % 7; - var dayIndex = (remainder + 7) % 7; - - var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; - return add_days(date, diff) - } - - var set_day = setDay; - - /** - * @category Day Helpers - * @summary Set the day of the year to the given date. - * - * @description - * Set the day of the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfYear - the day of the year of the new date - * @returns {Date} the new date with the day of the year setted - * - * @example - * // Set the 2nd day of the year to 2 July 2014: - * var result = setDayOfYear(new Date(2014, 6, 2), 2) - * //=> Thu Jan 02 2014 00:00:00 - */ - function setDayOfYear (dirtyDate, dirtyDayOfYear) { - var date = parse_1(dirtyDate); - var dayOfYear = Number(dirtyDayOfYear); - date.setMonth(0); - date.setDate(dayOfYear); - return date - } - - var set_day_of_year = setDayOfYear; - - /** - * @category Hour Helpers - * @summary Set the hours to the given date. - * - * @description - * Set the hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} hours - the hours of the new date - * @returns {Date} the new date with the hours setted - * - * @example - * // Set 4 hours to 1 September 2014 11:30:00: - * var result = setHours(new Date(2014, 8, 1, 11, 30), 4) - * //=> Mon Sep 01 2014 04:30:00 - */ - function setHours (dirtyDate, dirtyHours) { - var date = parse_1(dirtyDate); - var hours = Number(dirtyHours); - date.setHours(hours); - return date - } - - var set_hours = setHours; - - /** - * @category Weekday Helpers - * @summary Set the day of the ISO week to the given date. - * - * @description - * Set the day of the ISO week to the given date. - * ISO week starts with Monday. - * 7 is the index of Sunday, 1 is the index of Monday etc. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the ISO week of the new date - * @returns {Date} the new date with the day of the ISO week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setISODay(new Date(2014, 8, 1), 7) - * //=> Sun Sep 07 2014 00:00:00 - */ - function setISODay (dirtyDate, dirtyDay) { - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = get_iso_day(date); - var diff = day - currentDay; - return add_days(date, diff) - } - - var set_iso_day = setISODay; - - /** - * @category ISO Week Helpers - * @summary Set the ISO week to the given date. - * - * @description - * Set the ISO week to the given date, saving the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoWeek - the ISO week of the new date - * @returns {Date} the new date with the ISO week setted - * - * @example - * // Set the 53rd ISO week to 7 August 2004: - * var result = setISOWeek(new Date(2004, 7, 7), 53) - * //=> Sat Jan 01 2005 00:00:00 - */ - function setISOWeek (dirtyDate, dirtyISOWeek) { - var date = parse_1(dirtyDate); - var isoWeek = Number(dirtyISOWeek); - var diff = get_iso_week(date) - isoWeek; - date.setDate(date.getDate() - diff * 7); - return date - } - - var set_iso_week = setISOWeek; - - /** - * @category Millisecond Helpers - * @summary Set the milliseconds to the given date. - * - * @description - * Set the milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} milliseconds - the milliseconds of the new date - * @returns {Date} the new date with the milliseconds setted - * - * @example - * // Set 300 milliseconds to 1 September 2014 11:30:40.500: - * var result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300) - * //=> Mon Sep 01 2014 11:30:40.300 - */ - function setMilliseconds (dirtyDate, dirtyMilliseconds) { - var date = parse_1(dirtyDate); - var milliseconds = Number(dirtyMilliseconds); - date.setMilliseconds(milliseconds); - return date - } - - var set_milliseconds = setMilliseconds; - - /** - * @category Minute Helpers - * @summary Set the minutes to the given date. - * - * @description - * Set the minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} minutes - the minutes of the new date - * @returns {Date} the new date with the minutes setted - * - * @example - * // Set 45 minutes to 1 September 2014 11:30:40: - * var result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:45:40 - */ - function setMinutes (dirtyDate, dirtyMinutes) { - var date = parse_1(dirtyDate); - var minutes = Number(dirtyMinutes); - date.setMinutes(minutes); - return date - } - - var set_minutes = setMinutes; - - /** - * @category Month Helpers - * @summary Set the month to the given date. - * - * @description - * Set the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} month - the month of the new date - * @returns {Date} the new date with the month setted - * - * @example - * // Set February to 1 September 2014: - * var result = setMonth(new Date(2014, 8, 1), 1) - * //=> Sat Feb 01 2014 00:00:00 - */ - function setMonth (dirtyDate, dirtyMonth) { - var date = parse_1(dirtyDate); - var month = Number(dirtyMonth); - var year = date.getFullYear(); - var day = date.getDate(); - - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(year, month, 15); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(month, Math.min(day, daysInMonth)); - return date - } - - var set_month = setMonth; - - /** - * @category Quarter Helpers - * @summary Set the year quarter to the given date. - * - * @description - * Set the year quarter to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} quarter - the quarter of the new date - * @returns {Date} the new date with the quarter setted - * - * @example - * // Set the 2nd quarter to 2 July 2014: - * var result = setQuarter(new Date(2014, 6, 2), 2) - * //=> Wed Apr 02 2014 00:00:00 - */ - function setQuarter (dirtyDate, dirtyQuarter) { - var date = parse_1(dirtyDate); - var quarter = Number(dirtyQuarter); - var oldQuarter = Math.floor(date.getMonth() / 3) + 1; - var diff = quarter - oldQuarter; - return set_month(date, date.getMonth() + diff * 3) - } - - var set_quarter = setQuarter; - - /** - * @category Second Helpers - * @summary Set the seconds to the given date. - * - * @description - * Set the seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} seconds - the seconds of the new date - * @returns {Date} the new date with the seconds setted - * - * @example - * // Set 45 seconds to 1 September 2014 11:30:40: - * var result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:30:45 - */ - function setSeconds (dirtyDate, dirtySeconds) { - var date = parse_1(dirtyDate); - var seconds = Number(dirtySeconds); - date.setSeconds(seconds); - return date - } - - var set_seconds = setSeconds; - - /** - * @category Year Helpers - * @summary Set the year to the given date. - * - * @description - * Set the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} year - the year of the new date - * @returns {Date} the new date with the year setted - * - * @example - * // Set year 2013 to 1 September 2014: - * var result = setYear(new Date(2014, 8, 1), 2013) - * //=> Sun Sep 01 2013 00:00:00 - */ - function setYear (dirtyDate, dirtyYear) { - var date = parse_1(dirtyDate); - var year = Number(dirtyYear); - date.setFullYear(year); - return date - } - - var set_year = setYear; - - /** - * @category Month Helpers - * @summary Return the start of a month for the given date. - * - * @description - * Return the start of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a month - * - * @example - * // The start of a month for 2 September 2014 11:55:00: - * var result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - date.setDate(1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_month = startOfMonth; - - /** - * @category Day Helpers - * @summary Return the start of today. - * - * @description - * Return the start of today. - * - * @returns {Date} the start of today - * - * @example - * // If today is 6 October 2014: - * var result = startOfToday() - * //=> Mon Oct 6 2014 00:00:00 - */ - function startOfToday () { - return start_of_day(new Date()) - } - - var start_of_today = startOfToday; - - /** - * @category Day Helpers - * @summary Return the start of tomorrow. - * - * @description - * Return the start of tomorrow. - * - * @returns {Date} the start of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = startOfTomorrow() - * //=> Tue Oct 7 2014 00:00:00 - */ - function startOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_tomorrow = startOfTomorrow; - - /** - * @category Day Helpers - * @summary Return the start of yesterday. - * - * @description - * Return the start of yesterday. - * - * @returns {Date} the start of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = startOfYesterday() - * //=> Sun Oct 5 2014 00:00:00 - */ - function startOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_yesterday = startOfYesterday; - - /** - * @category Day Helpers - * @summary Subtract the specified number of days from the given date. - * - * @description - * Subtract the specified number of days from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be subtracted - * @returns {Date} the new date with the days subtracted - * - * @example - * // Subtract 10 days from 1 September 2014: - * var result = subDays(new Date(2014, 8, 1), 10) - * //=> Fri Aug 22 2014 00:00:00 - */ - function subDays (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_days(dirtyDate, -amount) - } - - var sub_days = subDays; - - /** - * @category Hour Helpers - * @summary Subtract the specified number of hours from the given date. - * - * @description - * Subtract the specified number of hours from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be subtracted - * @returns {Date} the new date with the hours subtracted - * - * @example - * // Subtract 2 hours from 11 July 2014 01:00:00: - * var result = subHours(new Date(2014, 6, 11, 1, 0), 2) - * //=> Thu Jul 10 2014 23:00:00 - */ - function subHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_hours(dirtyDate, -amount) - } - - var sub_hours = subHours; - - /** - * @category Millisecond Helpers - * @summary Subtract the specified number of milliseconds from the given date. - * - * @description - * Subtract the specified number of milliseconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be subtracted - * @returns {Date} the new date with the milliseconds subtracted - * - * @example - * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: - * var result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:29.250 - */ - function subMilliseconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, -amount) - } - - var sub_milliseconds = subMilliseconds; - - /** - * @category Minute Helpers - * @summary Subtract the specified number of minutes from the given date. - * - * @description - * Subtract the specified number of minutes from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be subtracted - * @returns {Date} the new date with the mintues subtracted - * - * @example - * // Subtract 30 minutes from 10 July 2014 12:00:00: - * var result = subMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 11:30:00 - */ - function subMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_minutes(dirtyDate, -amount) - } - - var sub_minutes = subMinutes; - - /** - * @category Month Helpers - * @summary Subtract the specified number of months from the given date. - * - * @description - * Subtract the specified number of months from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be subtracted - * @returns {Date} the new date with the months subtracted - * - * @example - * // Subtract 5 months from 1 February 2015: - * var result = subMonths(new Date(2015, 1, 1), 5) - * //=> Mon Sep 01 2014 00:00:00 - */ - function subMonths (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, -amount) - } - - var sub_months = subMonths; - - /** - * @category Quarter Helpers - * @summary Subtract the specified number of year quarters from the given date. - * - * @description - * Subtract the specified number of year quarters from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be subtracted - * @returns {Date} the new date with the quarters subtracted - * - * @example - * // Subtract 3 quarters from 1 September 2014: - * var result = subQuarters(new Date(2014, 8, 1), 3) - * //=> Sun Dec 01 2013 00:00:00 - */ - function subQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_quarters(dirtyDate, -amount) - } - - var sub_quarters = subQuarters; - - /** - * @category Second Helpers - * @summary Subtract the specified number of seconds from the given date. - * - * @description - * Subtract the specified number of seconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be subtracted - * @returns {Date} the new date with the seconds subtracted - * - * @example - * // Subtract 30 seconds from 10 July 2014 12:45:00: - * var result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:44:30 - */ - function subSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_seconds(dirtyDate, -amount) - } - - var sub_seconds = subSeconds; - - /** - * @category Week Helpers - * @summary Subtract the specified number of weeks from the given date. - * - * @description - * Subtract the specified number of weeks from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be subtracted - * @returns {Date} the new date with the weeks subtracted - * - * @example - * // Subtract 4 weeks from 1 September 2014: - * var result = subWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Aug 04 2014 00:00:00 - */ - function subWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_weeks(dirtyDate, -amount) - } - - var sub_weeks = subWeeks; - - /** - * @category Year Helpers - * @summary Subtract the specified number of years from the given date. - * - * @description - * Subtract the specified number of years from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be subtracted - * @returns {Date} the new date with the years subtracted - * - * @example - * // Subtract 5 years from 1 September 2014: - * var result = subYears(new Date(2014, 8, 1), 5) - * //=> Tue Sep 01 2009 00:00:00 - */ - function subYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_years(dirtyDate, -amount) - } - - var sub_years = subYears; - - var dateFns = { - addDays: add_days, - addHours: add_hours, - addISOYears: add_iso_years, - addMilliseconds: add_milliseconds, - addMinutes: add_minutes, - addMonths: add_months, - addQuarters: add_quarters, - addSeconds: add_seconds, - addWeeks: add_weeks, - addYears: add_years, - areRangesOverlapping: are_ranges_overlapping, - closestIndexTo: closest_index_to, - closestTo: closest_to, - compareAsc: compare_asc, - compareDesc: compare_desc, - differenceInCalendarDays: difference_in_calendar_days, - differenceInCalendarISOWeeks: difference_in_calendar_iso_weeks, - differenceInCalendarISOYears: difference_in_calendar_iso_years, - differenceInCalendarMonths: difference_in_calendar_months, - differenceInCalendarQuarters: difference_in_calendar_quarters, - differenceInCalendarWeeks: difference_in_calendar_weeks, - differenceInCalendarYears: difference_in_calendar_years, - differenceInDays: difference_in_days, - differenceInHours: difference_in_hours, - differenceInISOYears: difference_in_iso_years, - differenceInMilliseconds: difference_in_milliseconds, - differenceInMinutes: difference_in_minutes, - differenceInMonths: difference_in_months, - differenceInQuarters: difference_in_quarters, - differenceInSeconds: difference_in_seconds, - differenceInWeeks: difference_in_weeks, - differenceInYears: difference_in_years, - distanceInWords: distance_in_words, - distanceInWordsStrict: distance_in_words_strict, - distanceInWordsToNow: distance_in_words_to_now, - eachDay: each_day, - endOfDay: end_of_day, - endOfHour: end_of_hour, - endOfISOWeek: end_of_iso_week, - endOfISOYear: end_of_iso_year, - endOfMinute: end_of_minute, - endOfMonth: end_of_month, - endOfQuarter: end_of_quarter, - endOfSecond: end_of_second, - endOfToday: end_of_today, - endOfTomorrow: end_of_tomorrow, - endOfWeek: end_of_week, - endOfYear: end_of_year, - endOfYesterday: end_of_yesterday, - format: format_1, - getDate: get_date, - getDay: get_day, - getDayOfYear: get_day_of_year, - getDaysInMonth: get_days_in_month, - getDaysInYear: get_days_in_year, - getHours: get_hours, - getISODay: get_iso_day, - getISOWeek: get_iso_week, - getISOWeeksInYear: get_iso_weeks_in_year, - getISOYear: get_iso_year, - getMilliseconds: get_milliseconds, - getMinutes: get_minutes, - getMonth: get_month, - getOverlappingDaysInRanges: get_overlapping_days_in_ranges, - getQuarter: get_quarter, - getSeconds: get_seconds, - getTime: get_time, - getYear: get_year, - isAfter: is_after, - isBefore: is_before, - isDate: is_date, - isEqual: is_equal, - isFirstDayOfMonth: is_first_day_of_month, - isFriday: is_friday, - isFuture: is_future, - isLastDayOfMonth: is_last_day_of_month, - isLeapYear: is_leap_year, - isMonday: is_monday, - isPast: is_past, - isSameDay: is_same_day, - isSameHour: is_same_hour, - isSameISOWeek: is_same_iso_week, - isSameISOYear: is_same_iso_year, - isSameMinute: is_same_minute, - isSameMonth: is_same_month, - isSameQuarter: is_same_quarter, - isSameSecond: is_same_second, - isSameWeek: is_same_week, - isSameYear: is_same_year, - isSaturday: is_saturday, - isSunday: is_sunday, - isThisHour: is_this_hour, - isThisISOWeek: is_this_iso_week, - isThisISOYear: is_this_iso_year, - isThisMinute: is_this_minute, - isThisMonth: is_this_month, - isThisQuarter: is_this_quarter, - isThisSecond: is_this_second, - isThisWeek: is_this_week, - isThisYear: is_this_year, - isThursday: is_thursday, - isToday: is_today, - isTomorrow: is_tomorrow, - isTuesday: is_tuesday, - isValid: is_valid, - isWednesday: is_wednesday, - isWeekend: is_weekend, - isWithinRange: is_within_range, - isYesterday: is_yesterday, - lastDayOfISOWeek: last_day_of_iso_week, - lastDayOfISOYear: last_day_of_iso_year, - lastDayOfMonth: last_day_of_month, - lastDayOfQuarter: last_day_of_quarter, - lastDayOfWeek: last_day_of_week, - lastDayOfYear: last_day_of_year, - max: max_1, - min: min_1, - parse: parse_1, - setDate: set_date, - setDay: set_day, - setDayOfYear: set_day_of_year, - setHours: set_hours, - setISODay: set_iso_day, - setISOWeek: set_iso_week, - setISOYear: set_iso_year, - setMilliseconds: set_milliseconds, - setMinutes: set_minutes, - setMonth: set_month, - setQuarter: set_quarter, - setSeconds: set_seconds, - setYear: set_year, - startOfDay: start_of_day, - startOfHour: start_of_hour, - startOfISOWeek: start_of_iso_week, - startOfISOYear: start_of_iso_year, - startOfMinute: start_of_minute, - startOfMonth: start_of_month, - startOfQuarter: start_of_quarter, - startOfSecond: start_of_second, - startOfToday: start_of_today, - startOfTomorrow: start_of_tomorrow, - startOfWeek: start_of_week, - startOfYear: start_of_year, - startOfYesterday: start_of_yesterday, - subDays: sub_days, - subHours: sub_hours, - subISOYears: sub_iso_years, - subMilliseconds: sub_milliseconds, - subMinutes: sub_minutes, - subMonths: sub_months, - subQuarters: sub_quarters, - subSeconds: sub_seconds, - subWeeks: sub_weeks, - subYears: sub_years - }; - - const user = "user"; - - const date$2 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo$2 = `Sunnyvale ${user} ${date$2}`; - - const date$1 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo$1 = `@foo/lib/a ${date$1}`; - - const date = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo = `@foo/lib/a/a/a ${date}`; - - const fum = 'Wonderland'; - - var hello = 'Hello'; - - const name = 'Alice'; - - const json_key = "json_value"; - - console.log( - `${hello}, ${name} in ${fum} ${foo$2} ${foo$1} ${foo} ${far_a} ${far_a_b_c} ${json_key}`); - - // Test for sequences = false - class A { - a() { - return document.a; - } - } exports('A', A); - function inline_me() { - return 'abc'; - } - console.error(new A().a(), inline_me(), thing); - - } - }; -}); -//# sourceMappingURL=bundle.system.js.map
diff --git a/packages/rollup/test/integration/golden.umd.js.map.sha256_ b/packages/rollup/test/integration/golden.umd.js.map.sha256_ deleted file mode 100644 index 64cafd1..0000000 --- a/packages/rollup/test/integration/golden.umd.js.map.sha256_ +++ /dev/null
@@ -1 +0,0 @@ -15c50b14ddd8d514fd28c5a16cef55a5e5a8b1d949ba1d2f264895f8371fe5f5 \ No newline at end of file
diff --git a/packages/rollup/test/integration/golden.umd.js.sha256_ b/packages/rollup/test/integration/golden.umd.js.sha256_ deleted file mode 100755 index 8614fb1..0000000 --- a/packages/rollup/test/integration/golden.umd.js.sha256_ +++ /dev/null
@@ -1 +0,0 @@ -05b3f5575394321c22d04cea5d9fa8fe53f5ea06d686f05f7b5275016821d9cc \ No newline at end of file
diff --git a/packages/rollup/test/integration/golden.umd.js_ b/packages/rollup/test/integration/golden.umd.js_ deleted file mode 100644 index 30c8b09..0000000 --- a/packages/rollup/test/integration/golden.umd.js_ +++ /dev/null
@@ -1,5686 +0,0 @@ -/** - * @license A dummy license banner that goes at the top of the file. - * This is version <unknown> - */ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('some_global_var')) : - typeof define === 'function' && define.amd ? define(['exports', 'some_global_var'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.bundle = {}, global.runtime_name_of_global_var)); -}(this, (function (exports, some_global_var) { 'use strict'; - - var far_a = `@far/a`; - - var far_a_b_c = `@far/a/b/c`; - - var MILLISECONDS_IN_MINUTE$6 = 60000; - - /** - * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds. - * They usually appear for dates that denote time before the timezones were introduced - * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891 - * and GMT+01:00:00 after that date) - * - * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above, - * which would lead to incorrect calculations. - * - * This function returns the timezone offset in milliseconds that takes seconds in account. - */ - var getTimezoneOffsetInMilliseconds = function getTimezoneOffsetInMilliseconds (dirtyDate) { - var date = new Date(dirtyDate.getTime()); - var baseTimezoneOffset = date.getTimezoneOffset(); - date.setSeconds(0, 0); - var millisecondsPartOfTimezoneOffset = date.getTime() % MILLISECONDS_IN_MINUTE$6; - - return baseTimezoneOffset * MILLISECONDS_IN_MINUTE$6 + millisecondsPartOfTimezoneOffset - }; - - /** - * @category Common Helpers - * @summary Is the given argument an instance of Date? - * - * @description - * Is the given argument an instance of Date? - * - * @param {*} argument - the argument to check - * @returns {Boolean} the given argument is an instance of Date - * - * @example - * // Is 'mayonnaise' a Date? - * var result = isDate('mayonnaise') - * //=> false - */ - function isDate (argument) { - return argument instanceof Date - } - - var is_date = isDate; - - var MILLISECONDS_IN_HOUR$2 = 3600000; - var MILLISECONDS_IN_MINUTE$5 = 60000; - var DEFAULT_ADDITIONAL_DIGITS = 2; - - var parseTokenDateTimeDelimeter = /[T ]/; - var parseTokenPlainTime = /:/; - - // year tokens - var parseTokenYY = /^(\d{2})$/; - var parseTokensYYY = [ - /^([+-]\d{2})$/, // 0 additional digits - /^([+-]\d{3})$/, // 1 additional digit - /^([+-]\d{4})$/ // 2 additional digits - ]; - - var parseTokenYYYY = /^(\d{4})/; - var parseTokensYYYYY = [ - /^([+-]\d{4})/, // 0 additional digits - /^([+-]\d{5})/, // 1 additional digit - /^([+-]\d{6})/ // 2 additional digits - ]; - - // date tokens - var parseTokenMM = /^-(\d{2})$/; - var parseTokenDDD = /^-?(\d{3})$/; - var parseTokenMMDD = /^-?(\d{2})-?(\d{2})$/; - var parseTokenWww = /^-?W(\d{2})$/; - var parseTokenWwwD = /^-?W(\d{2})-?(\d{1})$/; - - // time tokens - var parseTokenHH = /^(\d{2}([.,]\d*)?)$/; - var parseTokenHHMM = /^(\d{2}):?(\d{2}([.,]\d*)?)$/; - var parseTokenHHMMSS = /^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/; - - // timezone tokens - var parseTokenTimezone = /([Z+-].*)$/; - var parseTokenTimezoneZ = /^(Z)$/; - var parseTokenTimezoneHH = /^([+-])(\d{2})$/; - var parseTokenTimezoneHHMM = /^([+-])(\d{2}):?(\d{2})$/; - - /** - * @category Common Helpers - * @summary Convert the given argument to an instance of Date. - * - * @description - * Convert the given argument to an instance of Date. - * - * If the argument is an instance of Date, the function returns its clone. - * - * If the argument is a number, it is treated as a timestamp. - * - * If an argument is a string, the function tries to parse it. - * Function accepts complete ISO 8601 formats as well as partial implementations. - * ISO 8601: http://en.wikipedia.org/wiki/ISO_8601 - * - * If all above fails, the function passes the given argument to Date constructor. - * - * @param {Date|String|Number} argument - the value to convert - * @param {Object} [options] - the object with options - * @param {0 | 1 | 2} [options.additionalDigits=2] - the additional number of digits in the extended year format - * @returns {Date} the parsed date in the local time zone - * - * @example - * // Convert string '2014-02-11T11:30:30' to date: - * var result = parse('2014-02-11T11:30:30') - * //=> Tue Feb 11 2014 11:30:30 - * - * @example - * // Parse string '+02014101', - * // if the additional number of digits in the extended year format is 1: - * var result = parse('+02014101', {additionalDigits: 1}) - * //=> Fri Apr 11 2014 00:00:00 - */ - function parse (argument, dirtyOptions) { - if (is_date(argument)) { - // Prevent the date to lose the milliseconds when passed to new Date() in IE10 - return new Date(argument.getTime()) - } else if (typeof argument !== 'string') { - return new Date(argument) - } - - var options = dirtyOptions || {}; - var additionalDigits = options.additionalDigits; - if (additionalDigits == null) { - additionalDigits = DEFAULT_ADDITIONAL_DIGITS; - } else { - additionalDigits = Number(additionalDigits); - } - - var dateStrings = splitDateString(argument); - - var parseYearResult = parseYear(dateStrings.date, additionalDigits); - var year = parseYearResult.year; - var restDateString = parseYearResult.restDateString; - - var date = parseDate(restDateString, year); - - if (date) { - var timestamp = date.getTime(); - var time = 0; - var offset; - - if (dateStrings.time) { - time = parseTime(dateStrings.time); - } - - if (dateStrings.timezone) { - offset = parseTimezone(dateStrings.timezone) * MILLISECONDS_IN_MINUTE$5; - } else { - var fullTime = timestamp + time; - var fullTimeDate = new Date(fullTime); - - offset = getTimezoneOffsetInMilliseconds(fullTimeDate); - - // Adjust time when it's coming from DST - var fullTimeDateNextDay = new Date(fullTime); - fullTimeDateNextDay.setDate(fullTimeDate.getDate() + 1); - var offsetDiff = - getTimezoneOffsetInMilliseconds(fullTimeDateNextDay) - - getTimezoneOffsetInMilliseconds(fullTimeDate); - if (offsetDiff > 0) { - offset += offsetDiff; - } - } - - return new Date(timestamp + time + offset) - } else { - return new Date(argument) - } - } - - function splitDateString (dateString) { - var dateStrings = {}; - var array = dateString.split(parseTokenDateTimeDelimeter); - var timeString; - - if (parseTokenPlainTime.test(array[0])) { - dateStrings.date = null; - timeString = array[0]; - } else { - dateStrings.date = array[0]; - timeString = array[1]; - } - - if (timeString) { - var token = parseTokenTimezone.exec(timeString); - if (token) { - dateStrings.time = timeString.replace(token[1], ''); - dateStrings.timezone = token[1]; - } else { - dateStrings.time = timeString; - } - } - - return dateStrings - } - - function parseYear (dateString, additionalDigits) { - var parseTokenYYY = parseTokensYYY[additionalDigits]; - var parseTokenYYYYY = parseTokensYYYYY[additionalDigits]; - - var token; - - // YYYY or ±YYYYY - token = parseTokenYYYY.exec(dateString) || parseTokenYYYYY.exec(dateString); - if (token) { - var yearString = token[1]; - return { - year: parseInt(yearString, 10), - restDateString: dateString.slice(yearString.length) - } - } - - // YY or ±YYY - token = parseTokenYY.exec(dateString) || parseTokenYYY.exec(dateString); - if (token) { - var centuryString = token[1]; - return { - year: parseInt(centuryString, 10) * 100, - restDateString: dateString.slice(centuryString.length) - } - } - - // Invalid ISO-formatted year - return { - year: null - } - } - - function parseDate (dateString, year) { - // Invalid ISO-formatted year - if (year === null) { - return null - } - - var token; - var date; - var month; - var week; - - // YYYY - if (dateString.length === 0) { - date = new Date(0); - date.setUTCFullYear(year); - return date - } - - // YYYY-MM - token = parseTokenMM.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - date.setUTCFullYear(year, month); - return date - } - - // YYYY-DDD or YYYYDDD - token = parseTokenDDD.exec(dateString); - if (token) { - date = new Date(0); - var dayOfYear = parseInt(token[1], 10); - date.setUTCFullYear(year, 0, dayOfYear); - return date - } - - // YYYY-MM-DD or YYYYMMDD - token = parseTokenMMDD.exec(dateString); - if (token) { - date = new Date(0); - month = parseInt(token[1], 10) - 1; - var day = parseInt(token[2], 10); - date.setUTCFullYear(year, month, day); - return date - } - - // YYYY-Www or YYYYWww - token = parseTokenWww.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - return dayOfISOYear(year, week) - } - - // YYYY-Www-D or YYYYWwwD - token = parseTokenWwwD.exec(dateString); - if (token) { - week = parseInt(token[1], 10) - 1; - var dayOfWeek = parseInt(token[2], 10) - 1; - return dayOfISOYear(year, week, dayOfWeek) - } - - // Invalid ISO-formatted date - return null - } - - function parseTime (timeString) { - var token; - var hours; - var minutes; - - // hh - token = parseTokenHH.exec(timeString); - if (token) { - hours = parseFloat(token[1].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 - } - - // hh:mm or hhmm - token = parseTokenHHMM.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseFloat(token[2].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 - } - - // hh:mm:ss or hhmmss - token = parseTokenHHMMSS.exec(timeString); - if (token) { - hours = parseInt(token[1], 10); - minutes = parseInt(token[2], 10); - var seconds = parseFloat(token[3].replace(',', '.')); - return (hours % 24) * MILLISECONDS_IN_HOUR$2 + - minutes * MILLISECONDS_IN_MINUTE$5 + - seconds * 1000 - } - - // Invalid ISO-formatted time - return null - } - - function parseTimezone (timezoneString) { - var token; - var absoluteOffset; - - // Z - token = parseTokenTimezoneZ.exec(timezoneString); - if (token) { - return 0 - } - - // ±hh - token = parseTokenTimezoneHH.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60; - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - // ±hh:mm or ±hhmm - token = parseTokenTimezoneHHMM.exec(timezoneString); - if (token) { - absoluteOffset = parseInt(token[2], 10) * 60 + parseInt(token[3], 10); - return (token[1] === '+') ? -absoluteOffset : absoluteOffset - } - - return 0 - } - - function dayOfISOYear (isoYear, week, day) { - week = week || 0; - day = day || 0; - var date = new Date(0); - date.setUTCFullYear(isoYear, 0, 4); - var fourthOfJanuaryDay = date.getUTCDay() || 7; - var diff = week * 7 + day + 1 - fourthOfJanuaryDay; - date.setUTCDate(date.getUTCDate() + diff); - return date - } - - var parse_1 = parse; - - /** - * @category Day Helpers - * @summary Add the specified number of days to the given date. - * - * @description - * Add the specified number of days to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be added - * @returns {Date} the new date with the days added - * - * @example - * // Add 10 days to 1 September 2014: - * var result = addDays(new Date(2014, 8, 1), 10) - * //=> Thu Sep 11 2014 00:00:00 - */ - function addDays (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - date.setDate(date.getDate() + amount); - return date - } - - var add_days = addDays; - - /** - * @category Millisecond Helpers - * @summary Add the specified number of milliseconds to the given date. - * - * @description - * Add the specified number of milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be added - * @returns {Date} the new date with the milliseconds added - * - * @example - * // Add 750 milliseconds to 10 July 2014 12:45:30.000: - * var result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:30.750 - */ - function addMilliseconds (dirtyDate, dirtyAmount) { - var timestamp = parse_1(dirtyDate).getTime(); - var amount = Number(dirtyAmount); - return new Date(timestamp + amount) - } - - var add_milliseconds = addMilliseconds; - - var MILLISECONDS_IN_HOUR$1 = 3600000; - - /** - * @category Hour Helpers - * @summary Add the specified number of hours to the given date. - * - * @description - * Add the specified number of hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be added - * @returns {Date} the new date with the hours added - * - * @example - * // Add 2 hours to 10 July 2014 23:00:00: - * var result = addHours(new Date(2014, 6, 10, 23, 0), 2) - * //=> Fri Jul 11 2014 01:00:00 - */ - function addHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_HOUR$1) - } - - var add_hours = addHours; - - /** - * @category Week Helpers - * @summary Return the start of a week for the given date. - * - * @description - * Return the start of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the start of a week - * - * @example - * // The start of a week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the start of the week for 2 September 2014 11:55:00: - * var result = startOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn; - - date.setDate(date.getDate() - diff); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_week = startOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the start of an ISO week for the given date. - * - * @description - * Return the start of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO week - * - * @example - * // The start of an ISO week for 2 September 2014 11:55:00: - * var result = startOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfISOWeek (dirtyDate) { - return start_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var start_of_iso_week = startOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the ISO week-numbering year of the given date. - * - * @description - * Get the ISO week-numbering year of the given date, - * which always starts 3 days before the year's first Thursday. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week-numbering year - * - * @example - * // Which ISO-week numbering year is 2 January 2005? - * var result = getISOYear(new Date(2005, 0, 2)) - * //=> 2004 - */ - function getISOYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var startOfNextYear = start_of_iso_week(fourthOfJanuaryOfNextYear); - - var fourthOfJanuaryOfThisYear = new Date(0); - fourthOfJanuaryOfThisYear.setFullYear(year, 0, 4); - fourthOfJanuaryOfThisYear.setHours(0, 0, 0, 0); - var startOfThisYear = start_of_iso_week(fourthOfJanuaryOfThisYear); - - if (date.getTime() >= startOfNextYear.getTime()) { - return year + 1 - } else if (date.getTime() >= startOfThisYear.getTime()) { - return year - } else { - return year - 1 - } - } - - var get_iso_year = getISOYear; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the start of an ISO week-numbering year for the given date. - * - * @description - * Return the start of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an ISO year - * - * @example - * // The start of an ISO week-numbering year for 2 July 2005: - * var result = startOfISOYear(new Date(2005, 6, 2)) - * //=> Mon Jan 03 2005 00:00:00 - */ - function startOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - return date - } - - var start_of_iso_year = startOfISOYear; - - /** - * @category Day Helpers - * @summary Return the start of a day for the given date. - * - * @description - * Return the start of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a day - * - * @example - * // The start of a day for 2 September 2014 11:55:00: - * var result = startOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 00:00:00 - */ - function startOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_day = startOfDay; - - var MILLISECONDS_IN_MINUTE$4 = 60000; - var MILLISECONDS_IN_DAY$1 = 86400000; - - /** - * @category Day Helpers - * @summary Get the number of calendar days between the given dates. - * - * @description - * Get the number of calendar days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar days - * - * @example - * // How many calendar days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInCalendarDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 366 - */ - function differenceInCalendarDays (dirtyDateLeft, dirtyDateRight) { - var startOfDayLeft = start_of_day(dirtyDateLeft); - var startOfDayRight = start_of_day(dirtyDateRight); - - var timestampLeft = startOfDayLeft.getTime() - - startOfDayLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - var timestampRight = startOfDayRight.getTime() - - startOfDayRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$4; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a day is not constant - // (e.g. it's different in the day of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_DAY$1) - } - - var difference_in_calendar_days = differenceInCalendarDays; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Set the ISO week-numbering year to the given date. - * - * @description - * Set the ISO week-numbering year to the given date, - * saving the week number and the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoYear - the ISO week-numbering year of the new date - * @returns {Date} the new date with the ISO week-numbering year setted - * - * @example - * // Set ISO week-numbering year 2007 to 29 December 2008: - * var result = setISOYear(new Date(2008, 11, 29), 2007) - * //=> Mon Jan 01 2007 00:00:00 - */ - function setISOYear (dirtyDate, dirtyISOYear) { - var date = parse_1(dirtyDate); - var isoYear = Number(dirtyISOYear); - var diff = difference_in_calendar_days(date, start_of_iso_year(date)); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(isoYear, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - date = start_of_iso_year(fourthOfJanuary); - date.setDate(date.getDate() + diff); - return date - } - - var set_iso_year = setISOYear; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Add the specified number of ISO week-numbering years to the given date. - * - * @description - * Add the specified number of ISO week-numbering years to the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be added - * @returns {Date} the new date with the ISO week-numbering years added - * - * @example - * // Add 5 ISO week-numbering years to 2 July 2010: - * var result = addISOYears(new Date(2010, 6, 2), 5) - * //=> Fri Jun 26 2015 00:00:00 - */ - function addISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return set_iso_year(dirtyDate, get_iso_year(dirtyDate) + amount) - } - - var add_iso_years = addISOYears; - - var MILLISECONDS_IN_MINUTE$3 = 60000; - - /** - * @category Minute Helpers - * @summary Add the specified number of minutes to the given date. - * - * @description - * Add the specified number of minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be added - * @returns {Date} the new date with the minutes added - * - * @example - * // Add 30 minutes to 10 July 2014 12:00:00: - * var result = addMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 12:30:00 - */ - function addMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * MILLISECONDS_IN_MINUTE$3) - } - - var add_minutes = addMinutes; - - /** - * @category Month Helpers - * @summary Get the number of days in a month of the given date. - * - * @description - * Get the number of days in a month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a month - * - * @example - * // How many days are in February 2000? - * var result = getDaysInMonth(new Date(2000, 1)) - * //=> 29 - */ - function getDaysInMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - var monthIndex = date.getMonth(); - var lastDayOfMonth = new Date(0); - lastDayOfMonth.setFullYear(year, monthIndex + 1, 0); - lastDayOfMonth.setHours(0, 0, 0, 0); - return lastDayOfMonth.getDate() - } - - var get_days_in_month = getDaysInMonth; - - /** - * @category Month Helpers - * @summary Add the specified number of months to the given date. - * - * @description - * Add the specified number of months to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be added - * @returns {Date} the new date with the months added - * - * @example - * // Add 5 months to 1 September 2014: - * var result = addMonths(new Date(2014, 8, 1), 5) - * //=> Sun Feb 01 2015 00:00:00 - */ - function addMonths (dirtyDate, dirtyAmount) { - var date = parse_1(dirtyDate); - var amount = Number(dirtyAmount); - var desiredMonth = date.getMonth() + amount; - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(date.getFullYear(), desiredMonth, 1); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(desiredMonth, Math.min(daysInMonth, date.getDate())); - return date - } - - var add_months = addMonths; - - /** - * @category Quarter Helpers - * @summary Add the specified number of year quarters to the given date. - * - * @description - * Add the specified number of year quarters to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be added - * @returns {Date} the new date with the quarters added - * - * @example - * // Add 1 quarter to 1 September 2014: - * var result = addQuarters(new Date(2014, 8, 1), 1) - * //=> Mon Dec 01 2014 00:00:00 - */ - function addQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var months = amount * 3; - return add_months(dirtyDate, months) - } - - var add_quarters = addQuarters; - - /** - * @category Second Helpers - * @summary Add the specified number of seconds to the given date. - * - * @description - * Add the specified number of seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be added - * @returns {Date} the new date with the seconds added - * - * @example - * // Add 30 seconds to 10 July 2014 12:45:00: - * var result = addSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:45:30 - */ - function addSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, amount * 1000) - } - - var add_seconds = addSeconds; - - /** - * @category Week Helpers - * @summary Add the specified number of weeks to the given date. - * - * @description - * Add the specified number of week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be added - * @returns {Date} the new date with the weeks added - * - * @example - * // Add 4 weeks to 1 September 2014: - * var result = addWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Sep 29 2014 00:00:00 - */ - function addWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - var days = amount * 7; - return add_days(dirtyDate, days) - } - - var add_weeks = addWeeks; - - /** - * @category Year Helpers - * @summary Add the specified number of years to the given date. - * - * @description - * Add the specified number of years to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be added - * @returns {Date} the new date with the years added - * - * @example - * // Add 5 years to 1 September 2014: - * var result = addYears(new Date(2014, 8, 1), 5) - * //=> Sun Sep 01 2019 00:00:00 - */ - function addYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, amount * 12) - } - - var add_years = addYears; - - /** - * @category Range Helpers - * @summary Is the given date range overlapping with another date range? - * - * @description - * Is the given date range overlapping with another date range? - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Boolean} whether the date ranges are overlapping - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> true - * - * @example - * // For non-overlapping date ranges: - * areRangesOverlapping( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> false - */ - function areRangesOverlapping (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return initialStartTime < comparedEndTime && comparedStartTime < initialEndTime - } - - var are_ranges_overlapping = areRangesOverlapping; - - /** - * @category Common Helpers - * @summary Return an index of the closest date from the array comparing to the given date. - * - * @description - * Return an index of the closest date from the array comparing to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Number} an index of the date closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015? - * var dateToCompare = new Date(2015, 8, 6) - * var datesArray = [ - * new Date(2015, 0, 1), - * new Date(2016, 0, 1), - * new Date(2017, 0, 1) - * ] - * var result = closestIndexTo(dateToCompare, datesArray) - * //=> 1 - */ - function closestIndexTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate, index) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = index; - minDistance = distance; - } - }); - - return result - } - - var closest_index_to = closestIndexTo; - - /** - * @category Common Helpers - * @summary Return a date from the array closest to the given date. - * - * @description - * Return a date from the array closest to the given date. - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date[]|String[]|Number[]} datesArray - the array to search - * @returns {Date} the date from the array closest to the given date - * @throws {TypeError} the second argument must be an instance of Array - * - * @example - * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030? - * var dateToCompare = new Date(2015, 8, 6) - * var result = closestTo(dateToCompare, [ - * new Date(2000, 0, 1), - * new Date(2030, 0, 1) - * ]) - * //=> Tue Jan 01 2030 00:00:00 - */ - function closestTo (dirtyDateToCompare, dirtyDatesArray) { - if (!(dirtyDatesArray instanceof Array)) { - throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array') - } - - var dateToCompare = parse_1(dirtyDateToCompare); - var timeToCompare = dateToCompare.getTime(); - - var result; - var minDistance; - - dirtyDatesArray.forEach(function (dirtyDate) { - var currentDate = parse_1(dirtyDate); - var distance = Math.abs(timeToCompare - currentDate.getTime()); - if (result === undefined || distance < minDistance) { - result = currentDate; - minDistance = distance; - } - }); - - return result - } - - var closest_to = closestTo; - - /** - * @category Common Helpers - * @summary Compare the two dates and return -1, 0 or 1. - * - * @description - * Compare the two dates and return 1 if the first date is after the second, - * -1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989: - * var result = compareAsc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> -1 - * - * @example - * // Sort the array of dates: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareAsc) - * //=> [ - * // Wed Feb 11 1987 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Sun Jul 02 1995 00:00:00 - * // ] - */ - function compareAsc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft < timeRight) { - return -1 - } else if (timeLeft > timeRight) { - return 1 - } else { - return 0 - } - } - - var compare_asc = compareAsc; - - /** - * @category Common Helpers - * @summary Compare the two dates reverse chronologically and return -1, 0 or 1. - * - * @description - * Compare the two dates and return -1 if the first date is after the second, - * 1 if the first date is before the second or 0 if dates are equal. - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Number} the result of the comparison - * - * @example - * // Compare 11 February 1987 and 10 July 1989 reverse chronologically: - * var result = compareDesc( - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ) - * //=> 1 - * - * @example - * // Sort the array of dates in reverse chronological order: - * var result = [ - * new Date(1995, 6, 2), - * new Date(1987, 1, 11), - * new Date(1989, 6, 10) - * ].sort(compareDesc) - * //=> [ - * // Sun Jul 02 1995 00:00:00, - * // Mon Jul 10 1989 00:00:00, - * // Wed Feb 11 1987 00:00:00 - * // ] - */ - function compareDesc (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var timeLeft = dateLeft.getTime(); - var dateRight = parse_1(dirtyDateRight); - var timeRight = dateRight.getTime(); - - if (timeLeft > timeRight) { - return -1 - } else if (timeLeft < timeRight) { - return 1 - } else { - return 0 - } - } - - var compare_desc = compareDesc; - - var MILLISECONDS_IN_MINUTE$2 = 60000; - var MILLISECONDS_IN_WEEK$3 = 604800000; - - /** - * @category ISO Week Helpers - * @summary Get the number of calendar ISO weeks between the given dates. - * - * @description - * Get the number of calendar ISO weeks between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO weeks - * - * @example - * // How many calendar ISO weeks are between 6 July 2014 and 21 July 2014? - * var result = differenceInCalendarISOWeeks( - * new Date(2014, 6, 21), - * new Date(2014, 6, 6) - * ) - * //=> 3 - */ - function differenceInCalendarISOWeeks (dirtyDateLeft, dirtyDateRight) { - var startOfISOWeekLeft = start_of_iso_week(dirtyDateLeft); - var startOfISOWeekRight = start_of_iso_week(dirtyDateRight); - - var timestampLeft = startOfISOWeekLeft.getTime() - - startOfISOWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - var timestampRight = startOfISOWeekRight.getTime() - - startOfISOWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$2; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$3) - } - - var difference_in_calendar_iso_weeks = differenceInCalendarISOWeeks; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of calendar ISO week-numbering years between the given dates. - * - * @description - * Get the number of calendar ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar ISO week-numbering years - * - * @example - * // How many calendar ISO week-numbering years are 1 January 2010 and 1 January 2012? - * var result = differenceInCalendarISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 2 - */ - function differenceInCalendarISOYears (dirtyDateLeft, dirtyDateRight) { - return get_iso_year(dirtyDateLeft) - get_iso_year(dirtyDateRight) - } - - var difference_in_calendar_iso_years = differenceInCalendarISOYears; - - /** - * @category Month Helpers - * @summary Get the number of calendar months between the given dates. - * - * @description - * Get the number of calendar months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar months - * - * @example - * // How many calendar months are between 31 January 2014 and 1 September 2014? - * var result = differenceInCalendarMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 8 - */ - function differenceInCalendarMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var monthDiff = dateLeft.getMonth() - dateRight.getMonth(); - - return yearDiff * 12 + monthDiff - } - - var difference_in_calendar_months = differenceInCalendarMonths; - - /** - * @category Quarter Helpers - * @summary Get the year quarter of the given date. - * - * @description - * Get the year quarter of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the quarter - * - * @example - * // Which quarter is 2 July 2014? - * var result = getQuarter(new Date(2014, 6, 2)) - * //=> 3 - */ - function getQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var quarter = Math.floor(date.getMonth() / 3) + 1; - return quarter - } - - var get_quarter = getQuarter; - - /** - * @category Quarter Helpers - * @summary Get the number of calendar quarters between the given dates. - * - * @description - * Get the number of calendar quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar quarters - * - * @example - * // How many calendar quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInCalendarQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 3 - */ - function differenceInCalendarQuarters (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var yearDiff = dateLeft.getFullYear() - dateRight.getFullYear(); - var quarterDiff = get_quarter(dateLeft) - get_quarter(dateRight); - - return yearDiff * 4 + quarterDiff - } - - var difference_in_calendar_quarters = differenceInCalendarQuarters; - - var MILLISECONDS_IN_MINUTE$1 = 60000; - var MILLISECONDS_IN_WEEK$2 = 604800000; - - /** - * @category Week Helpers - * @summary Get the number of calendar weeks between the given dates. - * - * @description - * Get the number of calendar weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Number} the number of calendar weeks - * - * @example - * // How many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 3 - * - * @example - * // If the week starts on Monday, - * // how many calendar weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInCalendarWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5), - * {weekStartsOn: 1} - * ) - * //=> 2 - */ - function differenceInCalendarWeeks (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var startOfWeekLeft = start_of_week(dirtyDateLeft, dirtyOptions); - var startOfWeekRight = start_of_week(dirtyDateRight, dirtyOptions); - - var timestampLeft = startOfWeekLeft.getTime() - - startOfWeekLeft.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - var timestampRight = startOfWeekRight.getTime() - - startOfWeekRight.getTimezoneOffset() * MILLISECONDS_IN_MINUTE$1; - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round((timestampLeft - timestampRight) / MILLISECONDS_IN_WEEK$2) - } - - var difference_in_calendar_weeks = differenceInCalendarWeeks; - - /** - * @category Year Helpers - * @summary Get the number of calendar years between the given dates. - * - * @description - * Get the number of calendar years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of calendar years - * - * @example - * // How many calendar years are between 31 December 2013 and 11 February 2015? - * var result = differenceInCalendarYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ - function differenceInCalendarYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - return dateLeft.getFullYear() - dateRight.getFullYear() - } - - var difference_in_calendar_years = differenceInCalendarYears; - - /** - * @category Day Helpers - * @summary Get the number of full days between the given dates. - * - * @description - * Get the number of full days between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full days - * - * @example - * // How many full days are between - * // 2 July 2011 23:00:00 and 2 July 2012 00:00:00? - * var result = differenceInDays( - * new Date(2012, 6, 2, 0, 0), - * new Date(2011, 6, 2, 23, 0) - * ) - * //=> 365 - */ - function differenceInDays (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_days(dateLeft, dateRight)); - dateLeft.setDate(dateLeft.getDate() - sign * difference); - - // Math.abs(diff in full days - diff in calendar days) === 1 if last calendar day is not full - // If so, result must be decreased by 1 in absolute value - var isLastDayNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastDayNotFull) - } - - var difference_in_days = differenceInDays; - - /** - * @category Millisecond Helpers - * @summary Get the number of milliseconds between the given dates. - * - * @description - * Get the number of milliseconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of milliseconds - * - * @example - * // How many milliseconds are between - * // 2 July 2014 12:30:20.600 and 2 July 2014 12:30:21.700? - * var result = differenceInMilliseconds( - * new Date(2014, 6, 2, 12, 30, 21, 700), - * new Date(2014, 6, 2, 12, 30, 20, 600) - * ) - * //=> 1100 - */ - function differenceInMilliseconds (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getTime() - dateRight.getTime() - } - - var difference_in_milliseconds = differenceInMilliseconds; - - var MILLISECONDS_IN_HOUR = 3600000; - - /** - * @category Hour Helpers - * @summary Get the number of hours between the given dates. - * - * @description - * Get the number of hours between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of hours - * - * @example - * // How many hours are between 2 July 2014 06:50:00 and 2 July 2014 19:00:00? - * var result = differenceInHours( - * new Date(2014, 6, 2, 19, 0), - * new Date(2014, 6, 2, 6, 50) - * ) - * //=> 12 - */ - function differenceInHours (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_HOUR; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_hours = differenceInHours; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Subtract the specified number of ISO week-numbering years from the given date. - * - * @description - * Subtract the specified number of ISO week-numbering years from the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of ISO week-numbering years to be subtracted - * @returns {Date} the new date with the ISO week-numbering years subtracted - * - * @example - * // Subtract 5 ISO week-numbering years from 1 September 2014: - * var result = subISOYears(new Date(2014, 8, 1), 5) - * //=> Mon Aug 31 2009 00:00:00 - */ - function subISOYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_iso_years(dirtyDate, -amount) - } - - var sub_iso_years = subISOYears; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of full ISO week-numbering years between the given dates. - * - * @description - * Get the number of full ISO week-numbering years between the given dates. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full ISO week-numbering years - * - * @example - * // How many full ISO week-numbering years are between 1 January 2010 and 1 January 2012? - * var result = differenceInISOYears( - * new Date(2012, 0, 1), - * new Date(2010, 0, 1) - * ) - * //=> 1 - */ - function differenceInISOYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_iso_years(dateLeft, dateRight)); - dateLeft = sub_iso_years(dateLeft, sign * difference); - - // Math.abs(diff in full ISO years - diff in calendar ISO years) === 1 - // if last calendar ISO year is not full - // If so, result must be decreased by 1 in absolute value - var isLastISOYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastISOYearNotFull) - } - - var difference_in_iso_years = differenceInISOYears; - - var MILLISECONDS_IN_MINUTE = 60000; - - /** - * @category Minute Helpers - * @summary Get the number of minutes between the given dates. - * - * @description - * Get the number of minutes between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of minutes - * - * @example - * // How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00? - * var result = differenceInMinutes( - * new Date(2014, 6, 2, 12, 20, 0), - * new Date(2014, 6, 2, 12, 7, 59) - * ) - * //=> 12 - */ - function differenceInMinutes (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / MILLISECONDS_IN_MINUTE; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_minutes = differenceInMinutes; - - /** - * @category Month Helpers - * @summary Get the number of full months between the given dates. - * - * @description - * Get the number of full months between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full months - * - * @example - * // How many full months are between 31 January 2014 and 1 September 2014? - * var result = differenceInMonths( - * new Date(2014, 8, 1), - * new Date(2014, 0, 31) - * ) - * //=> 7 - */ - function differenceInMonths (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_months(dateLeft, dateRight)); - dateLeft.setMonth(dateLeft.getMonth() - sign * difference); - - // Math.abs(diff in full months - diff in calendar months) === 1 if last calendar month is not full - // If so, result must be decreased by 1 in absolute value - var isLastMonthNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastMonthNotFull) - } - - var difference_in_months = differenceInMonths; - - /** - * @category Quarter Helpers - * @summary Get the number of full quarters between the given dates. - * - * @description - * Get the number of full quarters between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full quarters - * - * @example - * // How many full quarters are between 31 December 2013 and 2 July 2014? - * var result = differenceInQuarters( - * new Date(2014, 6, 2), - * new Date(2013, 11, 31) - * ) - * //=> 2 - */ - function differenceInQuarters (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_months(dirtyDateLeft, dirtyDateRight) / 3; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_quarters = differenceInQuarters; - - /** - * @category Second Helpers - * @summary Get the number of seconds between the given dates. - * - * @description - * Get the number of seconds between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of seconds - * - * @example - * // How many seconds are between - * // 2 July 2014 12:30:07.999 and 2 July 2014 12:30:20.000? - * var result = differenceInSeconds( - * new Date(2014, 6, 2, 12, 30, 20, 0), - * new Date(2014, 6, 2, 12, 30, 7, 999) - * ) - * //=> 12 - */ - function differenceInSeconds (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_milliseconds(dirtyDateLeft, dirtyDateRight) / 1000; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_seconds = differenceInSeconds; - - /** - * @category Week Helpers - * @summary Get the number of full weeks between the given dates. - * - * @description - * Get the number of full weeks between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full weeks - * - * @example - * // How many full weeks are between 5 July 2014 and 20 July 2014? - * var result = differenceInWeeks( - * new Date(2014, 6, 20), - * new Date(2014, 6, 5) - * ) - * //=> 2 - */ - function differenceInWeeks (dirtyDateLeft, dirtyDateRight) { - var diff = difference_in_days(dirtyDateLeft, dirtyDateRight) / 7; - return diff > 0 ? Math.floor(diff) : Math.ceil(diff) - } - - var difference_in_weeks = differenceInWeeks; - - /** - * @category Year Helpers - * @summary Get the number of full years between the given dates. - * - * @description - * Get the number of full years between the given dates. - * - * @param {Date|String|Number} dateLeft - the later date - * @param {Date|String|Number} dateRight - the earlier date - * @returns {Number} the number of full years - * - * @example - * // How many full years are between 31 December 2013 and 11 February 2015? - * var result = differenceInYears( - * new Date(2015, 1, 11), - * new Date(2013, 11, 31) - * ) - * //=> 1 - */ - function differenceInYears (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - - var sign = compare_asc(dateLeft, dateRight); - var difference = Math.abs(difference_in_calendar_years(dateLeft, dateRight)); - dateLeft.setFullYear(dateLeft.getFullYear() - sign * difference); - - // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full - // If so, result must be decreased by 1 in absolute value - var isLastYearNotFull = compare_asc(dateLeft, dateRight) === -sign; - return sign * (difference - isLastYearNotFull) - } - - var difference_in_years = differenceInYears; - - function buildDistanceInWordsLocale () { - var distanceInWordsLocale = { - lessThanXSeconds: { - one: 'less than a second', - other: 'less than {{count}} seconds' - }, - - xSeconds: { - one: '1 second', - other: '{{count}} seconds' - }, - - halfAMinute: 'half a minute', - - lessThanXMinutes: { - one: 'less than a minute', - other: 'less than {{count}} minutes' - }, - - xMinutes: { - one: '1 minute', - other: '{{count}} minutes' - }, - - aboutXHours: { - one: 'about 1 hour', - other: 'about {{count}} hours' - }, - - xHours: { - one: '1 hour', - other: '{{count}} hours' - }, - - xDays: { - one: '1 day', - other: '{{count}} days' - }, - - aboutXMonths: { - one: 'about 1 month', - other: 'about {{count}} months' - }, - - xMonths: { - one: '1 month', - other: '{{count}} months' - }, - - aboutXYears: { - one: 'about 1 year', - other: 'about {{count}} years' - }, - - xYears: { - one: '1 year', - other: '{{count}} years' - }, - - overXYears: { - one: 'over 1 year', - other: 'over {{count}} years' - }, - - almostXYears: { - one: 'almost 1 year', - other: 'almost {{count}} years' - } - }; - - function localize (token, count, options) { - options = options || {}; - - var result; - if (typeof distanceInWordsLocale[token] === 'string') { - result = distanceInWordsLocale[token]; - } else if (count === 1) { - result = distanceInWordsLocale[token].one; - } else { - result = distanceInWordsLocale[token].other.replace('{{count}}', count); - } - - if (options.addSuffix) { - if (options.comparison > 0) { - return 'in ' + result - } else { - return result + ' ago' - } - } - - return result - } - - return { - localize: localize - } - } - - var build_distance_in_words_locale = buildDistanceInWordsLocale; - - var commonFormatterKeys = [ - 'M', 'MM', 'Q', 'D', 'DD', 'DDD', 'DDDD', 'd', - 'E', 'W', 'WW', 'YY', 'YYYY', 'GG', 'GGGG', - 'H', 'HH', 'h', 'hh', 'm', 'mm', - 's', 'ss', 'S', 'SS', 'SSS', - 'Z', 'ZZ', 'X', 'x' - ]; - - function buildFormattingTokensRegExp (formatters) { - var formatterKeys = []; - for (var key in formatters) { - if (formatters.hasOwnProperty(key)) { - formatterKeys.push(key); - } - } - - var formattingTokens = commonFormatterKeys - .concat(formatterKeys) - .sort() - .reverse(); - var formattingTokensRegExp = new RegExp( - '(\\[[^\\[]*\\])|(\\\\)?' + '(' + formattingTokens.join('|') + '|.)', 'g' - ); - - return formattingTokensRegExp - } - - var build_formatting_tokens_reg_exp = buildFormattingTokensRegExp; - - function buildFormatLocale () { - // Note: in English, the names of days of the week and months are capitalized. - // If you are making a new locale based on this one, check if the same is true for the language you're working on. - // Generally, formatted dates should look like they are in the middle of a sentence, - // e.g. in Spanish language the weekdays and months should be in the lowercase. - var months3char = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - var monthsFull = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; - var weekdays2char = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']; - var weekdays3char = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; - var weekdaysFull = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; - var meridiemUppercase = ['AM', 'PM']; - var meridiemLowercase = ['am', 'pm']; - var meridiemFull = ['a.m.', 'p.m.']; - - var formatters = { - // Month: Jan, Feb, ..., Dec - 'MMM': function (date) { - return months3char[date.getMonth()] - }, - - // Month: January, February, ..., December - 'MMMM': function (date) { - return monthsFull[date.getMonth()] - }, - - // Day of week: Su, Mo, ..., Sa - 'dd': function (date) { - return weekdays2char[date.getDay()] - }, - - // Day of week: Sun, Mon, ..., Sat - 'ddd': function (date) { - return weekdays3char[date.getDay()] - }, - - // Day of week: Sunday, Monday, ..., Saturday - 'dddd': function (date) { - return weekdaysFull[date.getDay()] - }, - - // AM, PM - 'A': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemUppercase[1] : meridiemUppercase[0] - }, - - // am, pm - 'a': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemLowercase[1] : meridiemLowercase[0] - }, - - // a.m., p.m. - 'aa': function (date) { - return (date.getHours() / 12) >= 1 ? meridiemFull[1] : meridiemFull[0] - } - }; - - // Generate ordinal version of formatters: M -> Mo, D -> Do, etc. - var ordinalFormatters = ['M', 'D', 'DDD', 'd', 'Q', 'W']; - ordinalFormatters.forEach(function (formatterToken) { - formatters[formatterToken + 'o'] = function (date, formatters) { - return ordinal(formatters[formatterToken](date)) - }; - }); - - return { - formatters: formatters, - formattingTokensRegExp: build_formatting_tokens_reg_exp(formatters) - } - } - - function ordinal (number) { - var rem100 = number % 100; - if (rem100 > 20 || rem100 < 10) { - switch (rem100 % 10) { - case 1: - return number + 'st' - case 2: - return number + 'nd' - case 3: - return number + 'rd' - } - } - return number + 'th' - } - - var build_format_locale = buildFormatLocale; - - /** - * @category Locales - * @summary English locale. - */ - var en = { - distanceInWords: build_distance_in_words_locale(), - format: build_format_locale() - }; - - var MINUTES_IN_DAY$1 = 1440; - var MINUTES_IN_ALMOST_TWO_DAYS = 2520; - var MINUTES_IN_MONTH$1 = 43200; - var MINUTES_IN_TWO_MONTHS = 86400; - - /** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words. - * - * | Distance between dates | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance between dates | Result | - * |------------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWords( - * new Date(2014, 6, 2), - * new Date(2015, 0, 1) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00, including seconds? - * var result = distanceInWords( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWords( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> 'about 1 year ago' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWords( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ - function distanceInWords (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = Math.round(seconds / 60) - offset; - var months; - - // 0 up to 2 mins - if (minutes < 2) { - if (options.includeSeconds) { - if (seconds < 5) { - return localize('lessThanXSeconds', 5, localizeOptions) - } else if (seconds < 10) { - return localize('lessThanXSeconds', 10, localizeOptions) - } else if (seconds < 20) { - return localize('lessThanXSeconds', 20, localizeOptions) - } else if (seconds < 40) { - return localize('halfAMinute', null, localizeOptions) - } else if (seconds < 60) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', 1, localizeOptions) - } - } else { - if (minutes === 0) { - return localize('lessThanXMinutes', 1, localizeOptions) - } else { - return localize('xMinutes', minutes, localizeOptions) - } - } - - // 2 mins up to 0.75 hrs - } else if (minutes < 45) { - return localize('xMinutes', minutes, localizeOptions) - - // 0.75 hrs up to 1.5 hrs - } else if (minutes < 90) { - return localize('aboutXHours', 1, localizeOptions) - - // 1.5 hrs up to 24 hrs - } else if (minutes < MINUTES_IN_DAY$1) { - var hours = Math.round(minutes / 60); - return localize('aboutXHours', hours, localizeOptions) - - // 1 day up to 1.75 days - } else if (minutes < MINUTES_IN_ALMOST_TWO_DAYS) { - return localize('xDays', 1, localizeOptions) - - // 1.75 days up to 30 days - } else if (minutes < MINUTES_IN_MONTH$1) { - var days = Math.round(minutes / MINUTES_IN_DAY$1); - return localize('xDays', days, localizeOptions) - - // 1 month up to 2 months - } else if (minutes < MINUTES_IN_TWO_MONTHS) { - months = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('aboutXMonths', months, localizeOptions) - } - - months = difference_in_months(dateRight, dateLeft); - - // 2 months up to 12 months - if (months < 12) { - var nearestMonth = Math.round(minutes / MINUTES_IN_MONTH$1); - return localize('xMonths', nearestMonth, localizeOptions) - - // 1 year up to max Date - } else { - var monthsSinceStartOfYear = months % 12; - var years = Math.floor(months / 12); - - // N years up to 1 years 3 months - if (monthsSinceStartOfYear < 3) { - return localize('aboutXYears', years, localizeOptions) - - // N years 3 months up to N years 9 months - } else if (monthsSinceStartOfYear < 9) { - return localize('overXYears', years, localizeOptions) - - // N years 9 months up to N year 12 months - } else { - return localize('almostXYears', years + 1, localizeOptions) - } - } - } - - var distance_in_words = distanceInWords; - - var MINUTES_IN_DAY = 1440; - var MINUTES_IN_MONTH = 43200; - var MINUTES_IN_YEAR = 525600; - - /** - * @category Common Helpers - * @summary Return the distance between the given dates in words. - * - * @description - * Return the distance between the given dates in words, using strict units. - * This is like `distanceInWords`, but does not use helpers like 'almost', 'over', - * 'less than' and the like. - * - * | Distance between dates | Result | - * |------------------------|---------------------| - * | 0 ... 59 secs | [0..59] seconds | - * | 1 ... 59 mins | [1..59] minutes | - * | 1 ... 23 hrs | [1..23] hours | - * | 1 ... 29 days | [1..29] days | - * | 1 ... 11 months | [1..11] months | - * | 1 ... N years | [1..N] years | - * - * @param {Date|String|Number} dateToCompare - the date to compare with - * @param {Date|String|Number} date - the other date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.addSuffix=false] - result indicates if the second date is earlier or later than the first - * @param {'s'|'m'|'h'|'d'|'M'|'Y'} [options.unit] - if specified, will force a unit - * @param {'floor'|'ceil'|'round'} [options.partialMethod='floor'] - which way to round partial units - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // What is the distance between 2 July 2014 and 1 January 2015? - * var result = distanceInWordsStrict( - * new Date(2014, 6, 2), - * new Date(2015, 0, 2) - * ) - * //=> '6 months' - * - * @example - * // What is the distance between 1 January 2015 00:00:15 - * // and 1 January 2015 00:00:00? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 1, 0, 0, 15), - * new Date(2015, 0, 1, 0, 0, 0), - * ) - * //=> '15 seconds' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, with a suffix? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {addSuffix: true} - * ) - * //=> '1 year ago' - * - * @example - * // What is the distance from 1 January 2016 - * // to 1 January 2015, in minutes? - * var result = distanceInWordsStrict( - * new Date(2016, 0, 1), - * new Date(2015, 0, 1), - * {unit: 'm'} - * ) - * //=> '525600 minutes' - * - * @example - * // What is the distance from 1 January 2016 - * // to 28 January 2015, in months, rounded up? - * var result = distanceInWordsStrict( - * new Date(2015, 0, 28), - * new Date(2015, 0, 1), - * {unit: 'M', partialMethod: 'ceil'} - * ) - * //=> '1 month' - * - * @example - * // What is the distance between 1 August 2016 and 1 January 2015 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsStrict( - * new Date(2016, 7, 1), - * new Date(2015, 0, 1), - * {locale: eoLocale} - * ) - * //=> '1 jaro' - */ - function distanceInWordsStrict (dirtyDateToCompare, dirtyDate, dirtyOptions) { - var options = dirtyOptions || {}; - - var comparison = compare_desc(dirtyDateToCompare, dirtyDate); - - var locale = options.locale; - var localize = en.distanceInWords.localize; - if (locale && locale.distanceInWords && locale.distanceInWords.localize) { - localize = locale.distanceInWords.localize; - } - - var localizeOptions = { - addSuffix: Boolean(options.addSuffix), - comparison: comparison - }; - - var dateLeft, dateRight; - if (comparison > 0) { - dateLeft = parse_1(dirtyDateToCompare); - dateRight = parse_1(dirtyDate); - } else { - dateLeft = parse_1(dirtyDate); - dateRight = parse_1(dirtyDateToCompare); - } - - var unit; - var mathPartial = Math[options.partialMethod ? String(options.partialMethod) : 'floor']; - var seconds = difference_in_seconds(dateRight, dateLeft); - var offset = dateRight.getTimezoneOffset() - dateLeft.getTimezoneOffset(); - var minutes = mathPartial(seconds / 60) - offset; - var hours, days, months, years; - - if (options.unit) { - unit = String(options.unit); - } else { - if (minutes < 1) { - unit = 's'; - } else if (minutes < 60) { - unit = 'm'; - } else if (minutes < MINUTES_IN_DAY) { - unit = 'h'; - } else if (minutes < MINUTES_IN_MONTH) { - unit = 'd'; - } else if (minutes < MINUTES_IN_YEAR) { - unit = 'M'; - } else { - unit = 'Y'; - } - } - - // 0 up to 60 seconds - if (unit === 's') { - return localize('xSeconds', seconds, localizeOptions) - - // 1 up to 60 mins - } else if (unit === 'm') { - return localize('xMinutes', minutes, localizeOptions) - - // 1 up to 24 hours - } else if (unit === 'h') { - hours = mathPartial(minutes / 60); - return localize('xHours', hours, localizeOptions) - - // 1 up to 30 days - } else if (unit === 'd') { - days = mathPartial(minutes / MINUTES_IN_DAY); - return localize('xDays', days, localizeOptions) - - // 1 up to 12 months - } else if (unit === 'M') { - months = mathPartial(minutes / MINUTES_IN_MONTH); - return localize('xMonths', months, localizeOptions) - - // 1 year up to max Date - } else if (unit === 'Y') { - years = mathPartial(minutes / MINUTES_IN_YEAR); - return localize('xYears', years, localizeOptions) - } - - throw new Error('Unknown unit: ' + unit) - } - - var distance_in_words_strict = distanceInWordsStrict; - - /** - * @category Common Helpers - * @summary Return the distance between the given date and now in words. - * - * @description - * Return the distance between the given date and now in words. - * - * | Distance to now | Result | - * |-------------------------------------------------------------------|---------------------| - * | 0 ... 30 secs | less than a minute | - * | 30 secs ... 1 min 30 secs | 1 minute | - * | 1 min 30 secs ... 44 mins 30 secs | [2..44] minutes | - * | 44 mins ... 30 secs ... 89 mins 30 secs | about 1 hour | - * | 89 mins 30 secs ... 23 hrs 59 mins 30 secs | about [2..24] hours | - * | 23 hrs 59 mins 30 secs ... 41 hrs 59 mins 30 secs | 1 day | - * | 41 hrs 59 mins 30 secs ... 29 days 23 hrs 59 mins 30 secs | [2..30] days | - * | 29 days 23 hrs 59 mins 30 secs ... 44 days 23 hrs 59 mins 30 secs | about 1 month | - * | 44 days 23 hrs 59 mins 30 secs ... 59 days 23 hrs 59 mins 30 secs | about 2 months | - * | 59 days 23 hrs 59 mins 30 secs ... 1 yr | [2..12] months | - * | 1 yr ... 1 yr 3 months | about 1 year | - * | 1 yr 3 months ... 1 yr 9 month s | over 1 year | - * | 1 yr 9 months ... 2 yrs | almost 2 years | - * | N yrs ... N yrs 3 months | about N years | - * | N yrs 3 months ... N yrs 9 months | over N years | - * | N yrs 9 months ... N+1 yrs | almost N+1 years | - * - * With `options.includeSeconds == true`: - * | Distance to now | Result | - * |---------------------|----------------------| - * | 0 secs ... 5 secs | less than 5 seconds | - * | 5 secs ... 10 secs | less than 10 seconds | - * | 10 secs ... 20 secs | less than 20 seconds | - * | 20 secs ... 40 secs | half a minute | - * | 40 secs ... 60 secs | less than a minute | - * | 60 secs ... 90 secs | 1 minute | - * - * @param {Date|String|Number} date - the given date - * @param {Object} [options] - the object with options - * @param {Boolean} [options.includeSeconds=false] - distances less than a minute are more detailed - * @param {Boolean} [options.addSuffix=false] - result specifies if the second date is earlier or later than the first - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the distance in words - * - * @example - * // If today is 1 January 2015, what is the distance to 2 July 2014? - * var result = distanceInWordsToNow( - * new Date(2014, 6, 2) - * ) - * //=> '6 months' - * - * @example - * // If now is 1 January 2015 00:00:00, - * // what is the distance to 1 January 2015 00:00:15, including seconds? - * var result = distanceInWordsToNow( - * new Date(2015, 0, 1, 0, 0, 15), - * {includeSeconds: true} - * ) - * //=> 'less than 20 seconds' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 January 2016, with a suffix? - * var result = distanceInWordsToNow( - * new Date(2016, 0, 1), - * {addSuffix: true} - * ) - * //=> 'in about 1 year' - * - * @example - * // If today is 1 January 2015, - * // what is the distance to 1 August 2016 in Esperanto? - * var eoLocale = require('date-fns/locale/eo') - * var result = distanceInWordsToNow( - * new Date(2016, 7, 1), - * {locale: eoLocale} - * ) - * //=> 'pli ol 1 jaro' - */ - function distanceInWordsToNow (dirtyDate, dirtyOptions) { - return distance_in_words(Date.now(), dirtyDate, dirtyOptions) - } - - var distance_in_words_to_now = distanceInWordsToNow; - - /** - * @category Day Helpers - * @summary Return the array of dates within the specified range. - * - * @description - * Return the array of dates within the specified range. - * - * @param {Date|String|Number} startDate - the first date - * @param {Date|String|Number} endDate - the last date - * @param {Number} [step=1] - the step between each day - * @returns {Date[]} the array with starts of days from the day of startDate to the day of endDate - * @throws {Error} startDate cannot be after endDate - * - * @example - * // Each day between 6 October 2014 and 10 October 2014: - * var result = eachDay( - * new Date(2014, 9, 6), - * new Date(2014, 9, 10) - * ) - * //=> [ - * // Mon Oct 06 2014 00:00:00, - * // Tue Oct 07 2014 00:00:00, - * // Wed Oct 08 2014 00:00:00, - * // Thu Oct 09 2014 00:00:00, - * // Fri Oct 10 2014 00:00:00 - * // ] - */ - function eachDay (dirtyStartDate, dirtyEndDate, dirtyStep) { - var startDate = parse_1(dirtyStartDate); - var endDate = parse_1(dirtyEndDate); - var step = dirtyStep !== undefined ? dirtyStep : 1; - - var endTime = endDate.getTime(); - - if (startDate.getTime() > endTime) { - throw new Error('The first date cannot be after the second date') - } - - var dates = []; - - var currentDate = startDate; - currentDate.setHours(0, 0, 0, 0); - - while (currentDate.getTime() <= endTime) { - dates.push(parse_1(currentDate)); - currentDate.setDate(currentDate.getDate() + step); - } - - return dates - } - - var each_day = eachDay; - - /** - * @category Day Helpers - * @summary Return the end of a day for the given date. - * - * @description - * Return the end of a day for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a day - * - * @example - * // The end of a day for 2 September 2014 11:55:00: - * var result = endOfDay(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 02 2014 23:59:59.999 - */ - function endOfDay (dirtyDate) { - var date = parse_1(dirtyDate); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_day = endOfDay; - - /** - * @category Hour Helpers - * @summary Return the end of an hour for the given date. - * - * @description - * Return the end of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an hour - * - * @example - * // The end of an hour for 2 September 2014 11:55:00: - * var result = endOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:59:59.999 - */ - function endOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(59, 59, 999); - return date - } - - var end_of_hour = endOfHour; - - /** - * @category Week Helpers - * @summary Return the end of a week for the given date. - * - * @description - * Return the end of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the end of a week - * - * @example - * // The end of a week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 23:59:59.999 - * - * @example - * // If the week starts on Monday, the end of the week for 2 September 2014 11:55:00: - * var result = endOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 23:59:59.999 - */ - function endOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setDate(date.getDate() + diff); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_week = endOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the end of an ISO week for the given date. - * - * @description - * Return the end of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week - * - * @example - * // The end of an ISO week for 2 September 2014 11:55:00: - * var result = endOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 23:59:59.999 - */ - function endOfISOWeek (dirtyDate) { - return end_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var end_of_iso_week = endOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the end of an ISO week-numbering year for the given date. - * - * @description - * Return the end of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The end of an ISO week-numbering year for 2 July 2005: - * var result = endOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 23:59:59.999 - */ - function endOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuaryOfNextYear = new Date(0); - fourthOfJanuaryOfNextYear.setFullYear(year + 1, 0, 4); - fourthOfJanuaryOfNextYear.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuaryOfNextYear); - date.setMilliseconds(date.getMilliseconds() - 1); - return date - } - - var end_of_iso_year = endOfISOYear; - - /** - * @category Minute Helpers - * @summary Return the end of a minute for the given date. - * - * @description - * Return the end of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a minute - * - * @example - * // The end of a minute for 1 December 2014 22:15:45.400: - * var result = endOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:59.999 - */ - function endOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(59, 999); - return date - } - - var end_of_minute = endOfMinute; - - /** - * @category Month Helpers - * @summary Return the end of a month for the given date. - * - * @description - * Return the end of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a month - * - * @example - * // The end of a month for 2 September 2014 11:55:00: - * var result = endOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ - function endOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_month = endOfMonth; - - /** - * @category Quarter Helpers - * @summary Return the end of a year quarter for the given date. - * - * @description - * Return the end of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a quarter - * - * @example - * // The end of a quarter for 2 September 2014 11:55:00: - * var result = endOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 23:59:59.999 - */ - function endOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_quarter = endOfQuarter; - - /** - * @category Second Helpers - * @summary Return the end of a second for the given date. - * - * @description - * Return the end of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a second - * - * @example - * // The end of a second for 1 December 2014 22:15:45.400: - * var result = endOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.999 - */ - function endOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(999); - return date - } - - var end_of_second = endOfSecond; - - /** - * @category Day Helpers - * @summary Return the end of today. - * - * @description - * Return the end of today. - * - * @returns {Date} the end of today - * - * @example - * // If today is 6 October 2014: - * var result = endOfToday() - * //=> Mon Oct 6 2014 23:59:59.999 - */ - function endOfToday () { - return end_of_day(new Date()) - } - - var end_of_today = endOfToday; - - /** - * @category Day Helpers - * @summary Return the end of tomorrow. - * - * @description - * Return the end of tomorrow. - * - * @returns {Date} the end of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = endOfTomorrow() - * //=> Tue Oct 7 2014 23:59:59.999 - */ - function endOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_tomorrow = endOfTomorrow; - - /** - * @category Year Helpers - * @summary Return the end of a year for the given date. - * - * @description - * Return the end of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of a year - * - * @example - * // The end of a year for 2 September 2014 11:55:00: - * var result = endOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 23:59:59.999 - */ - function endOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_year = endOfYear; - - /** - * @category Day Helpers - * @summary Return the end of yesterday. - * - * @description - * Return the end of yesterday. - * - * @returns {Date} the end of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = endOfYesterday() - * //=> Sun Oct 5 2014 23:59:59.999 - */ - function endOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(23, 59, 59, 999); - return date - } - - var end_of_yesterday = endOfYesterday; - - /** - * @category Year Helpers - * @summary Return the start of a year for the given date. - * - * @description - * Return the start of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a year - * - * @example - * // The start of a year for 2 September 2014 11:55:00: - * var result = startOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Jan 01 2014 00:00:00 - */ - function startOfYear (dirtyDate) { - var cleanDate = parse_1(dirtyDate); - var date = new Date(0); - date.setFullYear(cleanDate.getFullYear(), 0, 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_year = startOfYear; - - /** - * @category Day Helpers - * @summary Get the day of the year of the given date. - * - * @description - * Get the day of the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of year - * - * @example - * // Which day of the year is 2 July 2014? - * var result = getDayOfYear(new Date(2014, 6, 2)) - * //=> 183 - */ - function getDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = difference_in_calendar_days(date, start_of_year(date)); - var dayOfYear = diff + 1; - return dayOfYear - } - - var get_day_of_year = getDayOfYear; - - var MILLISECONDS_IN_WEEK$1 = 604800000; - - /** - * @category ISO Week Helpers - * @summary Get the ISO week of the given date. - * - * @description - * Get the ISO week of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the ISO week - * - * @example - * // Which week of the ISO-week numbering year is 2 January 2005? - * var result = getISOWeek(new Date(2005, 0, 2)) - * //=> 53 - */ - function getISOWeek (dirtyDate) { - var date = parse_1(dirtyDate); - var diff = start_of_iso_week(date).getTime() - start_of_iso_year(date).getTime(); - - // Round the number of days to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1 - } - - var get_iso_week = getISOWeek; - - /** - * @category Common Helpers - * @summary Is the given date valid? - * - * @description - * Returns false if argument is Invalid Date and true otherwise. - * Invalid Date is a Date, whose time value is NaN. - * - * Time value of Date: http://es5.github.io/#x15.9.1.1 - * - * @param {Date} date - the date to check - * @returns {Boolean} the date is valid - * @throws {TypeError} argument must be an instance of Date - * - * @example - * // For the valid date: - * var result = isValid(new Date(2014, 1, 31)) - * //=> true - * - * @example - * // For the invalid date: - * var result = isValid(new Date('')) - * //=> false - */ - function isValid (dirtyDate) { - if (is_date(dirtyDate)) { - return !isNaN(dirtyDate) - } else { - throw new TypeError(toString.call(dirtyDate) + ' is not an instance of Date') - } - } - - var is_valid = isValid; - - /** - * @category Common Helpers - * @summary Format the date. - * - * @description - * Return the formatted date string in the given format. - * - * Accepted tokens: - * | Unit | Token | Result examples | - * |-------------------------|-------|----------------------------------| - * | Month | M | 1, 2, ..., 12 | - * | | Mo | 1st, 2nd, ..., 12th | - * | | MM | 01, 02, ..., 12 | - * | | MMM | Jan, Feb, ..., Dec | - * | | MMMM | January, February, ..., December | - * | Quarter | Q | 1, 2, 3, 4 | - * | | Qo | 1st, 2nd, 3rd, 4th | - * | Day of month | D | 1, 2, ..., 31 | - * | | Do | 1st, 2nd, ..., 31st | - * | | DD | 01, 02, ..., 31 | - * | Day of year | DDD | 1, 2, ..., 366 | - * | | DDDo | 1st, 2nd, ..., 366th | - * | | DDDD | 001, 002, ..., 366 | - * | Day of week | d | 0, 1, ..., 6 | - * | | do | 0th, 1st, ..., 6th | - * | | dd | Su, Mo, ..., Sa | - * | | ddd | Sun, Mon, ..., Sat | - * | | dddd | Sunday, Monday, ..., Saturday | - * | Day of ISO week | E | 1, 2, ..., 7 | - * | ISO week | W | 1, 2, ..., 53 | - * | | Wo | 1st, 2nd, ..., 53rd | - * | | WW | 01, 02, ..., 53 | - * | Year | YY | 00, 01, ..., 99 | - * | | YYYY | 1900, 1901, ..., 2099 | - * | ISO week-numbering year | GG | 00, 01, ..., 99 | - * | | GGGG | 1900, 1901, ..., 2099 | - * | AM/PM | A | AM, PM | - * | | a | am, pm | - * | | aa | a.m., p.m. | - * | Hour | H | 0, 1, ... 23 | - * | | HH | 00, 01, ... 23 | - * | | h | 1, 2, ..., 12 | - * | | hh | 01, 02, ..., 12 | - * | Minute | m | 0, 1, ..., 59 | - * | | mm | 00, 01, ..., 59 | - * | Second | s | 0, 1, ..., 59 | - * | | ss | 00, 01, ..., 59 | - * | 1/10 of second | S | 0, 1, ..., 9 | - * | 1/100 of second | SS | 00, 01, ..., 99 | - * | Millisecond | SSS | 000, 001, ..., 999 | - * | Timezone | Z | -01:00, +00:00, ... +12:00 | - * | | ZZ | -0100, +0000, ..., +1200 | - * | Seconds timestamp | X | 512969520 | - * | Milliseconds timestamp | x | 512969520900 | - * - * The characters wrapped in square brackets are escaped. - * - * The result may vary by locale. - * - * @param {Date|String|Number} date - the original date - * @param {String} [format='YYYY-MM-DDTHH:mm:ss.SSSZ'] - the string of tokens - * @param {Object} [options] - the object with options - * @param {Object} [options.locale=enLocale] - the locale object - * @returns {String} the formatted date string - * - * @example - * // Represent 11 February 2014 in middle-endian format: - * var result = format( - * new Date(2014, 1, 11), - * 'MM/DD/YYYY' - * ) - * //=> '02/11/2014' - * - * @example - * // Represent 2 July 2014 in Esperanto: - * var eoLocale = require('date-fns/locale/eo') - * var result = format( - * new Date(2014, 6, 2), - * 'Do [de] MMMM YYYY', - * {locale: eoLocale} - * ) - * //=> '2-a de julio 2014' - */ - function format (dirtyDate, dirtyFormatStr, dirtyOptions) { - var formatStr = dirtyFormatStr ? String(dirtyFormatStr) : 'YYYY-MM-DDTHH:mm:ss.SSSZ'; - var options = dirtyOptions || {}; - - var locale = options.locale; - var localeFormatters = en.format.formatters; - var formattingTokensRegExp = en.format.formattingTokensRegExp; - if (locale && locale.format && locale.format.formatters) { - localeFormatters = locale.format.formatters; - - if (locale.format.formattingTokensRegExp) { - formattingTokensRegExp = locale.format.formattingTokensRegExp; - } - } - - var date = parse_1(dirtyDate); - - if (!is_valid(date)) { - return 'Invalid Date' - } - - var formatFn = buildFormatFn(formatStr, localeFormatters, formattingTokensRegExp); - - return formatFn(date) - } - - var formatters = { - // Month: 1, 2, ..., 12 - 'M': function (date) { - return date.getMonth() + 1 - }, - - // Month: 01, 02, ..., 12 - 'MM': function (date) { - return addLeadingZeros(date.getMonth() + 1, 2) - }, - - // Quarter: 1, 2, 3, 4 - 'Q': function (date) { - return Math.ceil((date.getMonth() + 1) / 3) - }, - - // Day of month: 1, 2, ..., 31 - 'D': function (date) { - return date.getDate() - }, - - // Day of month: 01, 02, ..., 31 - 'DD': function (date) { - return addLeadingZeros(date.getDate(), 2) - }, - - // Day of year: 1, 2, ..., 366 - 'DDD': function (date) { - return get_day_of_year(date) - }, - - // Day of year: 001, 002, ..., 366 - 'DDDD': function (date) { - return addLeadingZeros(get_day_of_year(date), 3) - }, - - // Day of week: 0, 1, ..., 6 - 'd': function (date) { - return date.getDay() - }, - - // Day of ISO week: 1, 2, ..., 7 - 'E': function (date) { - return date.getDay() || 7 - }, - - // ISO week: 1, 2, ..., 53 - 'W': function (date) { - return get_iso_week(date) - }, - - // ISO week: 01, 02, ..., 53 - 'WW': function (date) { - return addLeadingZeros(get_iso_week(date), 2) - }, - - // Year: 00, 01, ..., 99 - 'YY': function (date) { - return addLeadingZeros(date.getFullYear(), 4).substr(2) - }, - - // Year: 1900, 1901, ..., 2099 - 'YYYY': function (date) { - return addLeadingZeros(date.getFullYear(), 4) - }, - - // ISO week-numbering year: 00, 01, ..., 99 - 'GG': function (date) { - return String(get_iso_year(date)).substr(2) - }, - - // ISO week-numbering year: 1900, 1901, ..., 2099 - 'GGGG': function (date) { - return get_iso_year(date) - }, - - // Hour: 0, 1, ... 23 - 'H': function (date) { - return date.getHours() - }, - - // Hour: 00, 01, ..., 23 - 'HH': function (date) { - return addLeadingZeros(date.getHours(), 2) - }, - - // Hour: 1, 2, ..., 12 - 'h': function (date) { - var hours = date.getHours(); - if (hours === 0) { - return 12 - } else if (hours > 12) { - return hours % 12 - } else { - return hours - } - }, - - // Hour: 01, 02, ..., 12 - 'hh': function (date) { - return addLeadingZeros(formatters['h'](date), 2) - }, - - // Minute: 0, 1, ..., 59 - 'm': function (date) { - return date.getMinutes() - }, - - // Minute: 00, 01, ..., 59 - 'mm': function (date) { - return addLeadingZeros(date.getMinutes(), 2) - }, - - // Second: 0, 1, ..., 59 - 's': function (date) { - return date.getSeconds() - }, - - // Second: 00, 01, ..., 59 - 'ss': function (date) { - return addLeadingZeros(date.getSeconds(), 2) - }, - - // 1/10 of second: 0, 1, ..., 9 - 'S': function (date) { - return Math.floor(date.getMilliseconds() / 100) - }, - - // 1/100 of second: 00, 01, ..., 99 - 'SS': function (date) { - return addLeadingZeros(Math.floor(date.getMilliseconds() / 10), 2) - }, - - // Millisecond: 000, 001, ..., 999 - 'SSS': function (date) { - return addLeadingZeros(date.getMilliseconds(), 3) - }, - - // Timezone: -01:00, +00:00, ... +12:00 - 'Z': function (date) { - return formatTimezone(date.getTimezoneOffset(), ':') - }, - - // Timezone: -0100, +0000, ... +1200 - 'ZZ': function (date) { - return formatTimezone(date.getTimezoneOffset()) - }, - - // Seconds timestamp: 512969520 - 'X': function (date) { - return Math.floor(date.getTime() / 1000) - }, - - // Milliseconds timestamp: 512969520900 - 'x': function (date) { - return date.getTime() - } - }; - - function buildFormatFn (formatStr, localeFormatters, formattingTokensRegExp) { - var array = formatStr.match(formattingTokensRegExp); - var length = array.length; - - var i; - var formatter; - for (i = 0; i < length; i++) { - formatter = localeFormatters[array[i]] || formatters[array[i]]; - if (formatter) { - array[i] = formatter; - } else { - array[i] = removeFormattingTokens(array[i]); - } - } - - return function (date) { - var output = ''; - for (var i = 0; i < length; i++) { - if (array[i] instanceof Function) { - output += array[i](date, formatters); - } else { - output += array[i]; - } - } - return output - } - } - - function removeFormattingTokens (input) { - if (input.match(/\[[\s\S]/)) { - return input.replace(/^\[|]$/g, '') - } - return input.replace(/\\/g, '') - } - - function formatTimezone (offset, delimeter) { - delimeter = delimeter || ''; - var sign = offset > 0 ? '-' : '+'; - var absOffset = Math.abs(offset); - var hours = Math.floor(absOffset / 60); - var minutes = absOffset % 60; - return sign + addLeadingZeros(hours, 2) + delimeter + addLeadingZeros(minutes, 2) - } - - function addLeadingZeros (number, targetLength) { - var output = Math.abs(number).toString(); - while (output.length < targetLength) { - output = '0' + output; - } - return output - } - - var format_1 = format; - - /** - * @category Day Helpers - * @summary Get the day of the month of the given date. - * - * @description - * Get the day of the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of month - * - * @example - * // Which day of the month is 29 February 2012? - * var result = getDate(new Date(2012, 1, 29)) - * //=> 29 - */ - function getDate (dirtyDate) { - var date = parse_1(dirtyDate); - var dayOfMonth = date.getDate(); - return dayOfMonth - } - - var get_date = getDate; - - /** - * @category Weekday Helpers - * @summary Get the day of the week of the given date. - * - * @description - * Get the day of the week of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of week - * - * @example - * // Which day of the week is 29 February 2012? - * var result = getDay(new Date(2012, 1, 29)) - * //=> 3 - */ - function getDay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day - } - - var get_day = getDay; - - /** - * @category Year Helpers - * @summary Is the given date in the leap year? - * - * @description - * Is the given date in the leap year? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the leap year - * - * @example - * // Is 1 September 2012 in the leap year? - * var result = isLeapYear(new Date(2012, 8, 1)) - * //=> true - */ - function isLeapYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year % 400 === 0 || year % 4 === 0 && year % 100 !== 0 - } - - var is_leap_year = isLeapYear; - - /** - * @category Year Helpers - * @summary Get the number of days in a year of the given date. - * - * @description - * Get the number of days in a year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of days in a year - * - * @example - * // How many days are in 2012? - * var result = getDaysInYear(new Date(2012, 0, 1)) - * //=> 366 - */ - function getDaysInYear (dirtyDate) { - return is_leap_year(dirtyDate) ? 366 : 365 - } - - var get_days_in_year = getDaysInYear; - - /** - * @category Hour Helpers - * @summary Get the hours of the given date. - * - * @description - * Get the hours of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the hours - * - * @example - * // Get the hours of 29 February 2012 11:45:00: - * var result = getHours(new Date(2012, 1, 29, 11, 45)) - * //=> 11 - */ - function getHours (dirtyDate) { - var date = parse_1(dirtyDate); - var hours = date.getHours(); - return hours - } - - var get_hours = getHours; - - /** - * @category Weekday Helpers - * @summary Get the day of the ISO week of the given date. - * - * @description - * Get the day of the ISO week of the given date, - * which is 7 for Sunday, 1 for Monday etc. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the day of ISO week - * - * @example - * // Which day of the ISO week is 26 February 2012? - * var result = getISODay(new Date(2012, 1, 26)) - * //=> 7 - */ - function getISODay (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - - if (day === 0) { - day = 7; - } - - return day - } - - var get_iso_day = getISODay; - - var MILLISECONDS_IN_WEEK = 604800000; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Get the number of weeks in an ISO week-numbering year of the given date. - * - * @description - * Get the number of weeks in an ISO week-numbering year of the given date. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the number of ISO weeks in a year - * - * @example - * // How many weeks are in ISO week-numbering year 2015? - * var result = getISOWeeksInYear(new Date(2015, 1, 11)) - * //=> 53 - */ - function getISOWeeksInYear (dirtyDate) { - var thisYear = start_of_iso_year(dirtyDate); - var nextYear = start_of_iso_year(add_weeks(thisYear, 60)); - var diff = nextYear.valueOf() - thisYear.valueOf(); - // Round the number of weeks to the nearest integer - // because the number of milliseconds in a week is not constant - // (e.g. it's different in the week of the daylight saving time clock shift) - return Math.round(diff / MILLISECONDS_IN_WEEK) - } - - var get_iso_weeks_in_year = getISOWeeksInYear; - - /** - * @category Millisecond Helpers - * @summary Get the milliseconds of the given date. - * - * @description - * Get the milliseconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the milliseconds - * - * @example - * // Get the milliseconds of 29 February 2012 11:45:05.123: - * var result = getMilliseconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 123 - */ - function getMilliseconds (dirtyDate) { - var date = parse_1(dirtyDate); - var milliseconds = date.getMilliseconds(); - return milliseconds - } - - var get_milliseconds = getMilliseconds; - - /** - * @category Minute Helpers - * @summary Get the minutes of the given date. - * - * @description - * Get the minutes of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the minutes - * - * @example - * // Get the minutes of 29 February 2012 11:45:05: - * var result = getMinutes(new Date(2012, 1, 29, 11, 45, 5)) - * //=> 45 - */ - function getMinutes (dirtyDate) { - var date = parse_1(dirtyDate); - var minutes = date.getMinutes(); - return minutes - } - - var get_minutes = getMinutes; - - /** - * @category Month Helpers - * @summary Get the month of the given date. - * - * @description - * Get the month of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the month - * - * @example - * // Which month is 29 February 2012? - * var result = getMonth(new Date(2012, 1, 29)) - * //=> 1 - */ - function getMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - return month - } - - var get_month = getMonth; - - var MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000; - - /** - * @category Range Helpers - * @summary Get the number of days that overlap in two date ranges - * - * @description - * Get the number of days that overlap in two date ranges - * - * @param {Date|String|Number} initialRangeStartDate - the start of the initial range - * @param {Date|String|Number} initialRangeEndDate - the end of the initial range - * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with - * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with - * @returns {Number} the number of days that overlap in two date ranges - * @throws {Error} startDate of a date range cannot be after its endDate - * - * @example - * // For overlapping date ranges adds 1 for each started overlapping day: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21) - * ) - * //=> 3 - * - * @example - * // For non-overlapping date ranges returns 0: - * getOverlappingDaysInRanges( - * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22) - * ) - * //=> 0 - */ - function getOverlappingDaysInRanges (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) { - var initialStartTime = parse_1(dirtyInitialRangeStartDate).getTime(); - var initialEndTime = parse_1(dirtyInitialRangeEndDate).getTime(); - var comparedStartTime = parse_1(dirtyComparedRangeStartDate).getTime(); - var comparedEndTime = parse_1(dirtyComparedRangeEndDate).getTime(); - - if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - var isOverlapping = initialStartTime < comparedEndTime && comparedStartTime < initialEndTime; - - if (!isOverlapping) { - return 0 - } - - var overlapStartDate = comparedStartTime < initialStartTime - ? initialStartTime - : comparedStartTime; - - var overlapEndDate = comparedEndTime > initialEndTime - ? initialEndTime - : comparedEndTime; - - var differenceInMs = overlapEndDate - overlapStartDate; - - return Math.ceil(differenceInMs / MILLISECONDS_IN_DAY) - } - - var get_overlapping_days_in_ranges = getOverlappingDaysInRanges; - - /** - * @category Second Helpers - * @summary Get the seconds of the given date. - * - * @description - * Get the seconds of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the seconds - * - * @example - * // Get the seconds of 29 February 2012 11:45:05.123: - * var result = getSeconds(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 5 - */ - function getSeconds (dirtyDate) { - var date = parse_1(dirtyDate); - var seconds = date.getSeconds(); - return seconds - } - - var get_seconds = getSeconds; - - /** - * @category Timestamp Helpers - * @summary Get the milliseconds timestamp of the given date. - * - * @description - * Get the milliseconds timestamp of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the timestamp - * - * @example - * // Get the timestamp of 29 February 2012 11:45:05.123: - * var result = getTime(new Date(2012, 1, 29, 11, 45, 5, 123)) - * //=> 1330515905123 - */ - function getTime (dirtyDate) { - var date = parse_1(dirtyDate); - var timestamp = date.getTime(); - return timestamp - } - - var get_time = getTime; - - /** - * @category Year Helpers - * @summary Get the year of the given date. - * - * @description - * Get the year of the given date. - * - * @param {Date|String|Number} date - the given date - * @returns {Number} the year - * - * @example - * // Which year is 2 July 2014? - * var result = getYear(new Date(2014, 6, 2)) - * //=> 2014 - */ - function getYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - return year - } - - var get_year = getYear; - - /** - * @category Common Helpers - * @summary Is the first date after the second one? - * - * @description - * Is the first date after the second one? - * - * @param {Date|String|Number} date - the date that should be after the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is after the second date - * - * @example - * // Is 10 July 1989 after 11 February 1987? - * var result = isAfter(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> true - */ - function isAfter (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() > dateToCompare.getTime() - } - - var is_after = isAfter; - - /** - * @category Common Helpers - * @summary Is the first date before the second one? - * - * @description - * Is the first date before the second one? - * - * @param {Date|String|Number} date - the date that should be before the other one to return true - * @param {Date|String|Number} dateToCompare - the date to compare with - * @returns {Boolean} the first date is before the second date - * - * @example - * // Is 10 July 1989 before 11 February 1987? - * var result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11)) - * //=> false - */ - function isBefore (dirtyDate, dirtyDateToCompare) { - var date = parse_1(dirtyDate); - var dateToCompare = parse_1(dirtyDateToCompare); - return date.getTime() < dateToCompare.getTime() - } - - var is_before = isBefore; - - /** - * @category Common Helpers - * @summary Are the given dates equal? - * - * @description - * Are the given dates equal? - * - * @param {Date|String|Number} dateLeft - the first date to compare - * @param {Date|String|Number} dateRight - the second date to compare - * @returns {Boolean} the dates are equal - * - * @example - * // Are 2 July 2014 06:30:45.000 and 2 July 2014 06:30:45.500 equal? - * var result = isEqual( - * new Date(2014, 6, 2, 6, 30, 45, 0) - * new Date(2014, 6, 2, 6, 30, 45, 500) - * ) - * //=> false - */ - function isEqual (dirtyLeftDate, dirtyRightDate) { - var dateLeft = parse_1(dirtyLeftDate); - var dateRight = parse_1(dirtyRightDate); - return dateLeft.getTime() === dateRight.getTime() - } - - var is_equal = isEqual; - - /** - * @category Month Helpers - * @summary Is the given date the first day of a month? - * - * @description - * Is the given date the first day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the first day of a month - * - * @example - * // Is 1 September 2014 the first day of a month? - * var result = isFirstDayOfMonth(new Date(2014, 8, 1)) - * //=> true - */ - function isFirstDayOfMonth (dirtyDate) { - return parse_1(dirtyDate).getDate() === 1 - } - - var is_first_day_of_month = isFirstDayOfMonth; - - /** - * @category Weekday Helpers - * @summary Is the given date Friday? - * - * @description - * Is the given date Friday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Friday - * - * @example - * // Is 26 September 2014 Friday? - * var result = isFriday(new Date(2014, 8, 26)) - * //=> true - */ - function isFriday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 5 - } - - var is_friday = isFriday; - - /** - * @category Common Helpers - * @summary Is the given date in the future? - * - * @description - * Is the given date in the future? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the future - * - * @example - * // If today is 6 October 2014, is 31 December 2014 in the future? - * var result = isFuture(new Date(2014, 11, 31)) - * //=> true - */ - function isFuture (dirtyDate) { - return parse_1(dirtyDate).getTime() > new Date().getTime() - } - - var is_future = isFuture; - - /** - * @category Month Helpers - * @summary Is the given date the last day of a month? - * - * @description - * Is the given date the last day of a month? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is the last day of a month - * - * @example - * // Is 28 February 2014 the last day of a month? - * var result = isLastDayOfMonth(new Date(2014, 1, 28)) - * //=> true - */ - function isLastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - return end_of_day(date).getTime() === end_of_month(date).getTime() - } - - var is_last_day_of_month = isLastDayOfMonth; - - /** - * @category Weekday Helpers - * @summary Is the given date Monday? - * - * @description - * Is the given date Monday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Monday - * - * @example - * // Is 22 September 2014 Monday? - * var result = isMonday(new Date(2014, 8, 22)) - * //=> true - */ - function isMonday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 1 - } - - var is_monday = isMonday; - - /** - * @category Common Helpers - * @summary Is the given date in the past? - * - * @description - * Is the given date in the past? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in the past - * - * @example - * // If today is 6 October 2014, is 2 July 2014 in the past? - * var result = isPast(new Date(2014, 6, 2)) - * //=> true - */ - function isPast (dirtyDate) { - return parse_1(dirtyDate).getTime() < new Date().getTime() - } - - var is_past = isPast; - - /** - * @category Day Helpers - * @summary Are the given dates in the same day? - * - * @description - * Are the given dates in the same day? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same day - * - * @example - * // Are 4 September 06:00:00 and 4 September 18:00:00 in the same day? - * var result = isSameDay( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 18, 0) - * ) - * //=> true - */ - function isSameDay (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfDay = start_of_day(dirtyDateLeft); - var dateRightStartOfDay = start_of_day(dirtyDateRight); - - return dateLeftStartOfDay.getTime() === dateRightStartOfDay.getTime() - } - - var is_same_day = isSameDay; - - /** - * @category Hour Helpers - * @summary Return the start of an hour for the given date. - * - * @description - * Return the start of an hour for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of an hour - * - * @example - * // The start of an hour for 2 September 2014 11:55:00: - * var result = startOfHour(new Date(2014, 8, 2, 11, 55)) - * //=> Tue Sep 02 2014 11:00:00 - */ - function startOfHour (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMinutes(0, 0, 0); - return date - } - - var start_of_hour = startOfHour; - - /** - * @category Hour Helpers - * @summary Are the given dates in the same hour? - * - * @description - * Are the given dates in the same hour? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same hour - * - * @example - * // Are 4 September 2014 06:00:00 and 4 September 06:30:00 in the same hour? - * var result = isSameHour( - * new Date(2014, 8, 4, 6, 0), - * new Date(2014, 8, 4, 6, 30) - * ) - * //=> true - */ - function isSameHour (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfHour = start_of_hour(dirtyDateLeft); - var dateRightStartOfHour = start_of_hour(dirtyDateRight); - - return dateLeftStartOfHour.getTime() === dateRightStartOfHour.getTime() - } - - var is_same_hour = isSameHour; - - /** - * @category Week Helpers - * @summary Are the given dates in the same week? - * - * @description - * Are the given dates in the same week? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the dates are in the same week - * - * @example - * // Are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4) - * ) - * //=> true - * - * @example - * // If week starts with Monday, - * // are 31 August 2014 and 4 September 2014 in the same week? - * var result = isSameWeek( - * new Date(2014, 7, 31), - * new Date(2014, 8, 4), - * {weekStartsOn: 1} - * ) - * //=> false - */ - function isSameWeek (dirtyDateLeft, dirtyDateRight, dirtyOptions) { - var dateLeftStartOfWeek = start_of_week(dirtyDateLeft, dirtyOptions); - var dateRightStartOfWeek = start_of_week(dirtyDateRight, dirtyOptions); - - return dateLeftStartOfWeek.getTime() === dateRightStartOfWeek.getTime() - } - - var is_same_week = isSameWeek; - - /** - * @category ISO Week Helpers - * @summary Are the given dates in the same ISO week? - * - * @description - * Are the given dates in the same ISO week? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week - * - * @example - * // Are 1 September 2014 and 7 September 2014 in the same ISO week? - * var result = isSameISOWeek( - * new Date(2014, 8, 1), - * new Date(2014, 8, 7) - * ) - * //=> true - */ - function isSameISOWeek (dirtyDateLeft, dirtyDateRight) { - return is_same_week(dirtyDateLeft, dirtyDateRight, {weekStartsOn: 1}) - } - - var is_same_iso_week = isSameISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Are the given dates in the same ISO week-numbering year? - * - * @description - * Are the given dates in the same ISO week-numbering year? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same ISO week-numbering year - * - * @example - * // Are 29 December 2003 and 2 January 2005 in the same ISO week-numbering year? - * var result = isSameISOYear( - * new Date(2003, 11, 29), - * new Date(2005, 0, 2) - * ) - * //=> true - */ - function isSameISOYear (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfYear = start_of_iso_year(dirtyDateLeft); - var dateRightStartOfYear = start_of_iso_year(dirtyDateRight); - - return dateLeftStartOfYear.getTime() === dateRightStartOfYear.getTime() - } - - var is_same_iso_year = isSameISOYear; - - /** - * @category Minute Helpers - * @summary Return the start of a minute for the given date. - * - * @description - * Return the start of a minute for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a minute - * - * @example - * // The start of a minute for 1 December 2014 22:15:45.400: - * var result = startOfMinute(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:00 - */ - function startOfMinute (dirtyDate) { - var date = parse_1(dirtyDate); - date.setSeconds(0, 0); - return date - } - - var start_of_minute = startOfMinute; - - /** - * @category Minute Helpers - * @summary Are the given dates in the same minute? - * - * @description - * Are the given dates in the same minute? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same minute - * - * @example - * // Are 4 September 2014 06:30:00 and 4 September 2014 06:30:15 - * // in the same minute? - * var result = isSameMinute( - * new Date(2014, 8, 4, 6, 30), - * new Date(2014, 8, 4, 6, 30, 15) - * ) - * //=> true - */ - function isSameMinute (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfMinute = start_of_minute(dirtyDateLeft); - var dateRightStartOfMinute = start_of_minute(dirtyDateRight); - - return dateLeftStartOfMinute.getTime() === dateRightStartOfMinute.getTime() - } - - var is_same_minute = isSameMinute; - - /** - * @category Month Helpers - * @summary Are the given dates in the same month? - * - * @description - * Are the given dates in the same month? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same month - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same month? - * var result = isSameMonth( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ - function isSameMonth (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() && - dateLeft.getMonth() === dateRight.getMonth() - } - - var is_same_month = isSameMonth; - - /** - * @category Quarter Helpers - * @summary Return the start of a year quarter for the given date. - * - * @description - * Return the start of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a quarter - * - * @example - * // The start of a quarter for 2 September 2014 11:55:00: - * var result = startOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Jul 01 2014 00:00:00 - */ - function startOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3; - date.setMonth(month, 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_quarter = startOfQuarter; - - /** - * @category Quarter Helpers - * @summary Are the given dates in the same year quarter? - * - * @description - * Are the given dates in the same year quarter? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same quarter - * - * @example - * // Are 1 January 2014 and 8 March 2014 in the same quarter? - * var result = isSameQuarter( - * new Date(2014, 0, 1), - * new Date(2014, 2, 8) - * ) - * //=> true - */ - function isSameQuarter (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfQuarter = start_of_quarter(dirtyDateLeft); - var dateRightStartOfQuarter = start_of_quarter(dirtyDateRight); - - return dateLeftStartOfQuarter.getTime() === dateRightStartOfQuarter.getTime() - } - - var is_same_quarter = isSameQuarter; - - /** - * @category Second Helpers - * @summary Return the start of a second for the given date. - * - * @description - * Return the start of a second for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a second - * - * @example - * // The start of a second for 1 December 2014 22:15:45.400: - * var result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400)) - * //=> Mon Dec 01 2014 22:15:45.000 - */ - function startOfSecond (dirtyDate) { - var date = parse_1(dirtyDate); - date.setMilliseconds(0); - return date - } - - var start_of_second = startOfSecond; - - /** - * @category Second Helpers - * @summary Are the given dates in the same second? - * - * @description - * Are the given dates in the same second? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same second - * - * @example - * // Are 4 September 2014 06:30:15.000 and 4 September 2014 06:30.15.500 - * // in the same second? - * var result = isSameSecond( - * new Date(2014, 8, 4, 6, 30, 15), - * new Date(2014, 8, 4, 6, 30, 15, 500) - * ) - * //=> true - */ - function isSameSecond (dirtyDateLeft, dirtyDateRight) { - var dateLeftStartOfSecond = start_of_second(dirtyDateLeft); - var dateRightStartOfSecond = start_of_second(dirtyDateRight); - - return dateLeftStartOfSecond.getTime() === dateRightStartOfSecond.getTime() - } - - var is_same_second = isSameSecond; - - /** - * @category Year Helpers - * @summary Are the given dates in the same year? - * - * @description - * Are the given dates in the same year? - * - * @param {Date|String|Number} dateLeft - the first date to check - * @param {Date|String|Number} dateRight - the second date to check - * @returns {Boolean} the dates are in the same year - * - * @example - * // Are 2 September 2014 and 25 September 2014 in the same year? - * var result = isSameYear( - * new Date(2014, 8, 2), - * new Date(2014, 8, 25) - * ) - * //=> true - */ - function isSameYear (dirtyDateLeft, dirtyDateRight) { - var dateLeft = parse_1(dirtyDateLeft); - var dateRight = parse_1(dirtyDateRight); - return dateLeft.getFullYear() === dateRight.getFullYear() - } - - var is_same_year = isSameYear; - - /** - * @category Weekday Helpers - * @summary Is the given date Saturday? - * - * @description - * Is the given date Saturday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Saturday - * - * @example - * // Is 27 September 2014 Saturday? - * var result = isSaturday(new Date(2014, 8, 27)) - * //=> true - */ - function isSaturday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 6 - } - - var is_saturday = isSaturday; - - /** - * @category Weekday Helpers - * @summary Is the given date Sunday? - * - * @description - * Is the given date Sunday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Sunday - * - * @example - * // Is 21 September 2014 Sunday? - * var result = isSunday(new Date(2014, 8, 21)) - * //=> true - */ - function isSunday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 0 - } - - var is_sunday = isSunday; - - /** - * @category Hour Helpers - * @summary Is the given date in the same hour as the current date? - * - * @description - * Is the given date in the same hour as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this hour - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:00:00 in this hour? - * var result = isThisHour(new Date(2014, 8, 25, 18)) - * //=> true - */ - function isThisHour (dirtyDate) { - return is_same_hour(new Date(), dirtyDate) - } - - var is_this_hour = isThisHour; - - /** - * @category ISO Week Helpers - * @summary Is the given date in the same ISO week as the current date? - * - * @description - * Is the given date in the same ISO week as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week - * - * @example - * // If today is 25 September 2014, is 22 September 2014 in this ISO week? - * var result = isThisISOWeek(new Date(2014, 8, 22)) - * //=> true - */ - function isThisISOWeek (dirtyDate) { - return is_same_iso_week(new Date(), dirtyDate) - } - - var is_this_iso_week = isThisISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Is the given date in the same ISO week-numbering year as the current date? - * - * @description - * Is the given date in the same ISO week-numbering year as the current date? - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this ISO week-numbering year - * - * @example - * // If today is 25 September 2014, - * // is 30 December 2013 in this ISO week-numbering year? - * var result = isThisISOYear(new Date(2013, 11, 30)) - * //=> true - */ - function isThisISOYear (dirtyDate) { - return is_same_iso_year(new Date(), dirtyDate) - } - - var is_this_iso_year = isThisISOYear; - - /** - * @category Minute Helpers - * @summary Is the given date in the same minute as the current date? - * - * @description - * Is the given date in the same minute as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this minute - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:00 in this minute? - * var result = isThisMinute(new Date(2014, 8, 25, 18, 30)) - * //=> true - */ - function isThisMinute (dirtyDate) { - return is_same_minute(new Date(), dirtyDate) - } - - var is_this_minute = isThisMinute; - - /** - * @category Month Helpers - * @summary Is the given date in the same month as the current date? - * - * @description - * Is the given date in the same month as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this month - * - * @example - * // If today is 25 September 2014, is 15 September 2014 in this month? - * var result = isThisMonth(new Date(2014, 8, 15)) - * //=> true - */ - function isThisMonth (dirtyDate) { - return is_same_month(new Date(), dirtyDate) - } - - var is_this_month = isThisMonth; - - /** - * @category Quarter Helpers - * @summary Is the given date in the same quarter as the current date? - * - * @description - * Is the given date in the same quarter as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this quarter - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this quarter? - * var result = isThisQuarter(new Date(2014, 6, 2)) - * //=> true - */ - function isThisQuarter (dirtyDate) { - return is_same_quarter(new Date(), dirtyDate) - } - - var is_this_quarter = isThisQuarter; - - /** - * @category Second Helpers - * @summary Is the given date in the same second as the current date? - * - * @description - * Is the given date in the same second as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this second - * - * @example - * // If now is 25 September 2014 18:30:15.500, - * // is 25 September 2014 18:30:15.000 in this second? - * var result = isThisSecond(new Date(2014, 8, 25, 18, 30, 15)) - * //=> true - */ - function isThisSecond (dirtyDate) { - return is_same_second(new Date(), dirtyDate) - } - - var is_this_second = isThisSecond; - - /** - * @category Week Helpers - * @summary Is the given date in the same week as the current date? - * - * @description - * Is the given date in the same week as the current date? - * - * @param {Date|String|Number} date - the date to check - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Boolean} the date is in this week - * - * @example - * // If today is 25 September 2014, is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21)) - * //=> true - * - * @example - * // If today is 25 September 2014 and week starts with Monday - * // is 21 September 2014 in this week? - * var result = isThisWeek(new Date(2014, 8, 21), {weekStartsOn: 1}) - * //=> false - */ - function isThisWeek (dirtyDate, dirtyOptions) { - return is_same_week(new Date(), dirtyDate, dirtyOptions) - } - - var is_this_week = isThisWeek; - - /** - * @category Year Helpers - * @summary Is the given date in the same year as the current date? - * - * @description - * Is the given date in the same year as the current date? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is in this year - * - * @example - * // If today is 25 September 2014, is 2 July 2014 in this year? - * var result = isThisYear(new Date(2014, 6, 2)) - * //=> true - */ - function isThisYear (dirtyDate) { - return is_same_year(new Date(), dirtyDate) - } - - var is_this_year = isThisYear; - - /** - * @category Weekday Helpers - * @summary Is the given date Thursday? - * - * @description - * Is the given date Thursday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Thursday - * - * @example - * // Is 25 September 2014 Thursday? - * var result = isThursday(new Date(2014, 8, 25)) - * //=> true - */ - function isThursday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 4 - } - - var is_thursday = isThursday; - - /** - * @category Day Helpers - * @summary Is the given date today? - * - * @description - * Is the given date today? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is today - * - * @example - * // If today is 6 October 2014, is 6 October 14:00:00 today? - * var result = isToday(new Date(2014, 9, 6, 14, 0)) - * //=> true - */ - function isToday (dirtyDate) { - return start_of_day(dirtyDate).getTime() === start_of_day(new Date()).getTime() - } - - var is_today = isToday; - - /** - * @category Day Helpers - * @summary Is the given date tomorrow? - * - * @description - * Is the given date tomorrow? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is tomorrow - * - * @example - * // If today is 6 October 2014, is 7 October 14:00:00 tomorrow? - * var result = isTomorrow(new Date(2014, 9, 7, 14, 0)) - * //=> true - */ - function isTomorrow (dirtyDate) { - var tomorrow = new Date(); - tomorrow.setDate(tomorrow.getDate() + 1); - return start_of_day(dirtyDate).getTime() === start_of_day(tomorrow).getTime() - } - - var is_tomorrow = isTomorrow; - - /** - * @category Weekday Helpers - * @summary Is the given date Tuesday? - * - * @description - * Is the given date Tuesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Tuesday - * - * @example - * // Is 23 September 2014 Tuesday? - * var result = isTuesday(new Date(2014, 8, 23)) - * //=> true - */ - function isTuesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 2 - } - - var is_tuesday = isTuesday; - - /** - * @category Weekday Helpers - * @summary Is the given date Wednesday? - * - * @description - * Is the given date Wednesday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is Wednesday - * - * @example - * // Is 24 September 2014 Wednesday? - * var result = isWednesday(new Date(2014, 8, 24)) - * //=> true - */ - function isWednesday (dirtyDate) { - return parse_1(dirtyDate).getDay() === 3 - } - - var is_wednesday = isWednesday; - - /** - * @category Weekday Helpers - * @summary Does the given date fall on a weekend? - * - * @description - * Does the given date fall on a weekend? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date falls on a weekend - * - * @example - * // Does 5 October 2014 fall on a weekend? - * var result = isWeekend(new Date(2014, 9, 5)) - * //=> true - */ - function isWeekend (dirtyDate) { - var date = parse_1(dirtyDate); - var day = date.getDay(); - return day === 0 || day === 6 - } - - var is_weekend = isWeekend; - - /** - * @category Range Helpers - * @summary Is the given date within the range? - * - * @description - * Is the given date within the range? - * - * @param {Date|String|Number} date - the date to check - * @param {Date|String|Number} startDate - the start of range - * @param {Date|String|Number} endDate - the end of range - * @returns {Boolean} the date is within the range - * @throws {Error} startDate cannot be after endDate - * - * @example - * // For the date within the range: - * isWithinRange( - * new Date(2014, 0, 3), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> true - * - * @example - * // For the date outside of the range: - * isWithinRange( - * new Date(2014, 0, 10), new Date(2014, 0, 1), new Date(2014, 0, 7) - * ) - * //=> false - */ - function isWithinRange (dirtyDate, dirtyStartDate, dirtyEndDate) { - var time = parse_1(dirtyDate).getTime(); - var startTime = parse_1(dirtyStartDate).getTime(); - var endTime = parse_1(dirtyEndDate).getTime(); - - if (startTime > endTime) { - throw new Error('The start of the range cannot be after the end of the range') - } - - return time >= startTime && time <= endTime - } - - var is_within_range = isWithinRange; - - /** - * @category Day Helpers - * @summary Is the given date yesterday? - * - * @description - * Is the given date yesterday? - * - * @param {Date|String|Number} date - the date to check - * @returns {Boolean} the date is yesterday - * - * @example - * // If today is 6 October 2014, is 5 October 14:00:00 yesterday? - * var result = isYesterday(new Date(2014, 9, 5, 14, 0)) - * //=> true - */ - function isYesterday (dirtyDate) { - var yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - return start_of_day(dirtyDate).getTime() === start_of_day(yesterday).getTime() - } - - var is_yesterday = isYesterday; - - /** - * @category Week Helpers - * @summary Return the last day of a week for the given date. - * - * @description - * Return the last day of a week for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the last day of a week - * - * @example - * // The last day of a week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sat Sep 06 2014 00:00:00 - * - * @example - * // If the week starts on Monday, the last day of the week for 2 September 2014 11:55:00: - * var result = lastDayOfWeek(new Date(2014, 8, 2, 11, 55, 0), {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ - function lastDayOfWeek (dirtyDate, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - - var date = parse_1(dirtyDate); - var day = date.getDay(); - var diff = (day < weekStartsOn ? -7 : 0) + 6 - (day - weekStartsOn); - - date.setHours(0, 0, 0, 0); - date.setDate(date.getDate() + diff); - return date - } - - var last_day_of_week = lastDayOfWeek; - - /** - * @category ISO Week Helpers - * @summary Return the last day of an ISO week for the given date. - * - * @description - * Return the last day of an ISO week for the given date. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of an ISO week - * - * @example - * // The last day of an ISO week for 2 September 2014 11:55:00: - * var result = lastDayOfISOWeek(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Sun Sep 07 2014 00:00:00 - */ - function lastDayOfISOWeek (dirtyDate) { - return last_day_of_week(dirtyDate, {weekStartsOn: 1}) - } - - var last_day_of_iso_week = lastDayOfISOWeek; - - /** - * @category ISO Week-Numbering Year Helpers - * @summary Return the last day of an ISO week-numbering year for the given date. - * - * @description - * Return the last day of an ISO week-numbering year, - * which always starts 3 days before the year's first Thursday. - * The result will be in the local timezone. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the end of an ISO week-numbering year - * - * @example - * // The last day of an ISO week-numbering year for 2 July 2005: - * var result = lastDayOfISOYear(new Date(2005, 6, 2)) - * //=> Sun Jan 01 2006 00:00:00 - */ - function lastDayOfISOYear (dirtyDate) { - var year = get_iso_year(dirtyDate); - var fourthOfJanuary = new Date(0); - fourthOfJanuary.setFullYear(year + 1, 0, 4); - fourthOfJanuary.setHours(0, 0, 0, 0); - var date = start_of_iso_week(fourthOfJanuary); - date.setDate(date.getDate() - 1); - return date - } - - var last_day_of_iso_year = lastDayOfISOYear; - - /** - * @category Month Helpers - * @summary Return the last day of a month for the given date. - * - * @description - * Return the last day of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a month - * - * @example - * // The last day of a month for 2 September 2014 11:55:00: - * var result = lastDayOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ - function lastDayOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - var month = date.getMonth(); - date.setFullYear(date.getFullYear(), month + 1, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_month = lastDayOfMonth; - - /** - * @category Quarter Helpers - * @summary Return the last day of a year quarter for the given date. - * - * @description - * Return the last day of a year quarter for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a quarter - * - * @example - * // The last day of a quarter for 2 September 2014 11:55:00: - * var result = lastDayOfQuarter(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Tue Sep 30 2014 00:00:00 - */ - function lastDayOfQuarter (dirtyDate) { - var date = parse_1(dirtyDate); - var currentMonth = date.getMonth(); - var month = currentMonth - currentMonth % 3 + 3; - date.setMonth(month, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_quarter = lastDayOfQuarter; - - /** - * @category Year Helpers - * @summary Return the last day of a year for the given date. - * - * @description - * Return the last day of a year for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the last day of a year - * - * @example - * // The last day of a year for 2 September 2014 11:55:00: - * var result = lastDayOfYear(new Date(2014, 8, 2, 11, 55, 00)) - * //=> Wed Dec 31 2014 00:00:00 - */ - function lastDayOfYear (dirtyDate) { - var date = parse_1(dirtyDate); - var year = date.getFullYear(); - date.setFullYear(year + 1, 0, 0); - date.setHours(0, 0, 0, 0); - return date - } - - var last_day_of_year = lastDayOfYear; - - /** - * @category Common Helpers - * @summary Return the latest of the given dates. - * - * @description - * Return the latest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the latest of the dates - * - * @example - * // Which of these dates is the latest? - * var result = max( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Sun Jul 02 1995 00:00:00 - */ - function max () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var latestTimestamp = Math.max.apply(null, dates); - return new Date(latestTimestamp) - } - - var max_1 = max; - - /** - * @category Common Helpers - * @summary Return the earliest of the given dates. - * - * @description - * Return the earliest of the given dates. - * - * @param {...(Date|String|Number)} dates - the dates to compare - * @returns {Date} the earliest of the dates - * - * @example - * // Which of these dates is the earliest? - * var result = min( - * new Date(1989, 6, 10), - * new Date(1987, 1, 11), - * new Date(1995, 6, 2), - * new Date(1990, 0, 1) - * ) - * //=> Wed Feb 11 1987 00:00:00 - */ - function min () { - var dirtyDates = Array.prototype.slice.call(arguments); - var dates = dirtyDates.map(function (dirtyDate) { - return parse_1(dirtyDate) - }); - var earliestTimestamp = Math.min.apply(null, dates); - return new Date(earliestTimestamp) - } - - var min_1 = min; - - /** - * @category Day Helpers - * @summary Set the day of the month to the given date. - * - * @description - * Set the day of the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfMonth - the day of the month of the new date - * @returns {Date} the new date with the day of the month setted - * - * @example - * // Set the 30th day of the month to 1 September 2014: - * var result = setDate(new Date(2014, 8, 1), 30) - * //=> Tue Sep 30 2014 00:00:00 - */ - function setDate (dirtyDate, dirtyDayOfMonth) { - var date = parse_1(dirtyDate); - var dayOfMonth = Number(dirtyDayOfMonth); - date.setDate(dayOfMonth); - return date - } - - var set_date = setDate; - - /** - * @category Weekday Helpers - * @summary Set the day of the week to the given date. - * - * @description - * Set the day of the week to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the week of the new date - * @param {Object} [options] - the object with options - * @param {Number} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) - * @returns {Date} the new date with the day of the week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0) - * //=> Sun Aug 31 2014 00:00:00 - * - * @example - * // If week starts with Monday, set Sunday to 1 September 2014: - * var result = setDay(new Date(2014, 8, 1), 0, {weekStartsOn: 1}) - * //=> Sun Sep 07 2014 00:00:00 - */ - function setDay (dirtyDate, dirtyDay, dirtyOptions) { - var weekStartsOn = dirtyOptions ? (Number(dirtyOptions.weekStartsOn) || 0) : 0; - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = date.getDay(); - - var remainder = day % 7; - var dayIndex = (remainder + 7) % 7; - - var diff = (dayIndex < weekStartsOn ? 7 : 0) + day - currentDay; - return add_days(date, diff) - } - - var set_day = setDay; - - /** - * @category Day Helpers - * @summary Set the day of the year to the given date. - * - * @description - * Set the day of the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} dayOfYear - the day of the year of the new date - * @returns {Date} the new date with the day of the year setted - * - * @example - * // Set the 2nd day of the year to 2 July 2014: - * var result = setDayOfYear(new Date(2014, 6, 2), 2) - * //=> Thu Jan 02 2014 00:00:00 - */ - function setDayOfYear (dirtyDate, dirtyDayOfYear) { - var date = parse_1(dirtyDate); - var dayOfYear = Number(dirtyDayOfYear); - date.setMonth(0); - date.setDate(dayOfYear); - return date - } - - var set_day_of_year = setDayOfYear; - - /** - * @category Hour Helpers - * @summary Set the hours to the given date. - * - * @description - * Set the hours to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} hours - the hours of the new date - * @returns {Date} the new date with the hours setted - * - * @example - * // Set 4 hours to 1 September 2014 11:30:00: - * var result = setHours(new Date(2014, 8, 1, 11, 30), 4) - * //=> Mon Sep 01 2014 04:30:00 - */ - function setHours (dirtyDate, dirtyHours) { - var date = parse_1(dirtyDate); - var hours = Number(dirtyHours); - date.setHours(hours); - return date - } - - var set_hours = setHours; - - /** - * @category Weekday Helpers - * @summary Set the day of the ISO week to the given date. - * - * @description - * Set the day of the ISO week to the given date. - * ISO week starts with Monday. - * 7 is the index of Sunday, 1 is the index of Monday etc. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} day - the day of the ISO week of the new date - * @returns {Date} the new date with the day of the ISO week setted - * - * @example - * // Set Sunday to 1 September 2014: - * var result = setISODay(new Date(2014, 8, 1), 7) - * //=> Sun Sep 07 2014 00:00:00 - */ - function setISODay (dirtyDate, dirtyDay) { - var date = parse_1(dirtyDate); - var day = Number(dirtyDay); - var currentDay = get_iso_day(date); - var diff = day - currentDay; - return add_days(date, diff) - } - - var set_iso_day = setISODay; - - /** - * @category ISO Week Helpers - * @summary Set the ISO week to the given date. - * - * @description - * Set the ISO week to the given date, saving the weekday number. - * - * ISO week-numbering year: http://en.wikipedia.org/wiki/ISO_week_date - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} isoWeek - the ISO week of the new date - * @returns {Date} the new date with the ISO week setted - * - * @example - * // Set the 53rd ISO week to 7 August 2004: - * var result = setISOWeek(new Date(2004, 7, 7), 53) - * //=> Sat Jan 01 2005 00:00:00 - */ - function setISOWeek (dirtyDate, dirtyISOWeek) { - var date = parse_1(dirtyDate); - var isoWeek = Number(dirtyISOWeek); - var diff = get_iso_week(date) - isoWeek; - date.setDate(date.getDate() - diff * 7); - return date - } - - var set_iso_week = setISOWeek; - - /** - * @category Millisecond Helpers - * @summary Set the milliseconds to the given date. - * - * @description - * Set the milliseconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} milliseconds - the milliseconds of the new date - * @returns {Date} the new date with the milliseconds setted - * - * @example - * // Set 300 milliseconds to 1 September 2014 11:30:40.500: - * var result = setMilliseconds(new Date(2014, 8, 1, 11, 30, 40, 500), 300) - * //=> Mon Sep 01 2014 11:30:40.300 - */ - function setMilliseconds (dirtyDate, dirtyMilliseconds) { - var date = parse_1(dirtyDate); - var milliseconds = Number(dirtyMilliseconds); - date.setMilliseconds(milliseconds); - return date - } - - var set_milliseconds = setMilliseconds; - - /** - * @category Minute Helpers - * @summary Set the minutes to the given date. - * - * @description - * Set the minutes to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} minutes - the minutes of the new date - * @returns {Date} the new date with the minutes setted - * - * @example - * // Set 45 minutes to 1 September 2014 11:30:40: - * var result = setMinutes(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:45:40 - */ - function setMinutes (dirtyDate, dirtyMinutes) { - var date = parse_1(dirtyDate); - var minutes = Number(dirtyMinutes); - date.setMinutes(minutes); - return date - } - - var set_minutes = setMinutes; - - /** - * @category Month Helpers - * @summary Set the month to the given date. - * - * @description - * Set the month to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} month - the month of the new date - * @returns {Date} the new date with the month setted - * - * @example - * // Set February to 1 September 2014: - * var result = setMonth(new Date(2014, 8, 1), 1) - * //=> Sat Feb 01 2014 00:00:00 - */ - function setMonth (dirtyDate, dirtyMonth) { - var date = parse_1(dirtyDate); - var month = Number(dirtyMonth); - var year = date.getFullYear(); - var day = date.getDate(); - - var dateWithDesiredMonth = new Date(0); - dateWithDesiredMonth.setFullYear(year, month, 15); - dateWithDesiredMonth.setHours(0, 0, 0, 0); - var daysInMonth = get_days_in_month(dateWithDesiredMonth); - // Set the last day of the new month - // if the original date was the last day of the longer month - date.setMonth(month, Math.min(day, daysInMonth)); - return date - } - - var set_month = setMonth; - - /** - * @category Quarter Helpers - * @summary Set the year quarter to the given date. - * - * @description - * Set the year quarter to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} quarter - the quarter of the new date - * @returns {Date} the new date with the quarter setted - * - * @example - * // Set the 2nd quarter to 2 July 2014: - * var result = setQuarter(new Date(2014, 6, 2), 2) - * //=> Wed Apr 02 2014 00:00:00 - */ - function setQuarter (dirtyDate, dirtyQuarter) { - var date = parse_1(dirtyDate); - var quarter = Number(dirtyQuarter); - var oldQuarter = Math.floor(date.getMonth() / 3) + 1; - var diff = quarter - oldQuarter; - return set_month(date, date.getMonth() + diff * 3) - } - - var set_quarter = setQuarter; - - /** - * @category Second Helpers - * @summary Set the seconds to the given date. - * - * @description - * Set the seconds to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} seconds - the seconds of the new date - * @returns {Date} the new date with the seconds setted - * - * @example - * // Set 45 seconds to 1 September 2014 11:30:40: - * var result = setSeconds(new Date(2014, 8, 1, 11, 30, 40), 45) - * //=> Mon Sep 01 2014 11:30:45 - */ - function setSeconds (dirtyDate, dirtySeconds) { - var date = parse_1(dirtyDate); - var seconds = Number(dirtySeconds); - date.setSeconds(seconds); - return date - } - - var set_seconds = setSeconds; - - /** - * @category Year Helpers - * @summary Set the year to the given date. - * - * @description - * Set the year to the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} year - the year of the new date - * @returns {Date} the new date with the year setted - * - * @example - * // Set year 2013 to 1 September 2014: - * var result = setYear(new Date(2014, 8, 1), 2013) - * //=> Sun Sep 01 2013 00:00:00 - */ - function setYear (dirtyDate, dirtyYear) { - var date = parse_1(dirtyDate); - var year = Number(dirtyYear); - date.setFullYear(year); - return date - } - - var set_year = setYear; - - /** - * @category Month Helpers - * @summary Return the start of a month for the given date. - * - * @description - * Return the start of a month for the given date. - * The result will be in the local timezone. - * - * @param {Date|String|Number} date - the original date - * @returns {Date} the start of a month - * - * @example - * // The start of a month for 2 September 2014 11:55:00: - * var result = startOfMonth(new Date(2014, 8, 2, 11, 55, 0)) - * //=> Mon Sep 01 2014 00:00:00 - */ - function startOfMonth (dirtyDate) { - var date = parse_1(dirtyDate); - date.setDate(1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_month = startOfMonth; - - /** - * @category Day Helpers - * @summary Return the start of today. - * - * @description - * Return the start of today. - * - * @returns {Date} the start of today - * - * @example - * // If today is 6 October 2014: - * var result = startOfToday() - * //=> Mon Oct 6 2014 00:00:00 - */ - function startOfToday () { - return start_of_day(new Date()) - } - - var start_of_today = startOfToday; - - /** - * @category Day Helpers - * @summary Return the start of tomorrow. - * - * @description - * Return the start of tomorrow. - * - * @returns {Date} the start of tomorrow - * - * @example - * // If today is 6 October 2014: - * var result = startOfTomorrow() - * //=> Tue Oct 7 2014 00:00:00 - */ - function startOfTomorrow () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day + 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_tomorrow = startOfTomorrow; - - /** - * @category Day Helpers - * @summary Return the start of yesterday. - * - * @description - * Return the start of yesterday. - * - * @returns {Date} the start of yesterday - * - * @example - * // If today is 6 October 2014: - * var result = startOfYesterday() - * //=> Sun Oct 5 2014 00:00:00 - */ - function startOfYesterday () { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth(); - var day = now.getDate(); - - var date = new Date(0); - date.setFullYear(year, month, day - 1); - date.setHours(0, 0, 0, 0); - return date - } - - var start_of_yesterday = startOfYesterday; - - /** - * @category Day Helpers - * @summary Subtract the specified number of days from the given date. - * - * @description - * Subtract the specified number of days from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of days to be subtracted - * @returns {Date} the new date with the days subtracted - * - * @example - * // Subtract 10 days from 1 September 2014: - * var result = subDays(new Date(2014, 8, 1), 10) - * //=> Fri Aug 22 2014 00:00:00 - */ - function subDays (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_days(dirtyDate, -amount) - } - - var sub_days = subDays; - - /** - * @category Hour Helpers - * @summary Subtract the specified number of hours from the given date. - * - * @description - * Subtract the specified number of hours from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of hours to be subtracted - * @returns {Date} the new date with the hours subtracted - * - * @example - * // Subtract 2 hours from 11 July 2014 01:00:00: - * var result = subHours(new Date(2014, 6, 11, 1, 0), 2) - * //=> Thu Jul 10 2014 23:00:00 - */ - function subHours (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_hours(dirtyDate, -amount) - } - - var sub_hours = subHours; - - /** - * @category Millisecond Helpers - * @summary Subtract the specified number of milliseconds from the given date. - * - * @description - * Subtract the specified number of milliseconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of milliseconds to be subtracted - * @returns {Date} the new date with the milliseconds subtracted - * - * @example - * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000: - * var result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750) - * //=> Thu Jul 10 2014 12:45:29.250 - */ - function subMilliseconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_milliseconds(dirtyDate, -amount) - } - - var sub_milliseconds = subMilliseconds; - - /** - * @category Minute Helpers - * @summary Subtract the specified number of minutes from the given date. - * - * @description - * Subtract the specified number of minutes from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of minutes to be subtracted - * @returns {Date} the new date with the mintues subtracted - * - * @example - * // Subtract 30 minutes from 10 July 2014 12:00:00: - * var result = subMinutes(new Date(2014, 6, 10, 12, 0), 30) - * //=> Thu Jul 10 2014 11:30:00 - */ - function subMinutes (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_minutes(dirtyDate, -amount) - } - - var sub_minutes = subMinutes; - - /** - * @category Month Helpers - * @summary Subtract the specified number of months from the given date. - * - * @description - * Subtract the specified number of months from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of months to be subtracted - * @returns {Date} the new date with the months subtracted - * - * @example - * // Subtract 5 months from 1 February 2015: - * var result = subMonths(new Date(2015, 1, 1), 5) - * //=> Mon Sep 01 2014 00:00:00 - */ - function subMonths (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_months(dirtyDate, -amount) - } - - var sub_months = subMonths; - - /** - * @category Quarter Helpers - * @summary Subtract the specified number of year quarters from the given date. - * - * @description - * Subtract the specified number of year quarters from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of quarters to be subtracted - * @returns {Date} the new date with the quarters subtracted - * - * @example - * // Subtract 3 quarters from 1 September 2014: - * var result = subQuarters(new Date(2014, 8, 1), 3) - * //=> Sun Dec 01 2013 00:00:00 - */ - function subQuarters (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_quarters(dirtyDate, -amount) - } - - var sub_quarters = subQuarters; - - /** - * @category Second Helpers - * @summary Subtract the specified number of seconds from the given date. - * - * @description - * Subtract the specified number of seconds from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of seconds to be subtracted - * @returns {Date} the new date with the seconds subtracted - * - * @example - * // Subtract 30 seconds from 10 July 2014 12:45:00: - * var result = subSeconds(new Date(2014, 6, 10, 12, 45, 0), 30) - * //=> Thu Jul 10 2014 12:44:30 - */ - function subSeconds (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_seconds(dirtyDate, -amount) - } - - var sub_seconds = subSeconds; - - /** - * @category Week Helpers - * @summary Subtract the specified number of weeks from the given date. - * - * @description - * Subtract the specified number of weeks from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of weeks to be subtracted - * @returns {Date} the new date with the weeks subtracted - * - * @example - * // Subtract 4 weeks from 1 September 2014: - * var result = subWeeks(new Date(2014, 8, 1), 4) - * //=> Mon Aug 04 2014 00:00:00 - */ - function subWeeks (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_weeks(dirtyDate, -amount) - } - - var sub_weeks = subWeeks; - - /** - * @category Year Helpers - * @summary Subtract the specified number of years from the given date. - * - * @description - * Subtract the specified number of years from the given date. - * - * @param {Date|String|Number} date - the date to be changed - * @param {Number} amount - the amount of years to be subtracted - * @returns {Date} the new date with the years subtracted - * - * @example - * // Subtract 5 years from 1 September 2014: - * var result = subYears(new Date(2014, 8, 1), 5) - * //=> Tue Sep 01 2009 00:00:00 - */ - function subYears (dirtyDate, dirtyAmount) { - var amount = Number(dirtyAmount); - return add_years(dirtyDate, -amount) - } - - var sub_years = subYears; - - var dateFns = { - addDays: add_days, - addHours: add_hours, - addISOYears: add_iso_years, - addMilliseconds: add_milliseconds, - addMinutes: add_minutes, - addMonths: add_months, - addQuarters: add_quarters, - addSeconds: add_seconds, - addWeeks: add_weeks, - addYears: add_years, - areRangesOverlapping: are_ranges_overlapping, - closestIndexTo: closest_index_to, - closestTo: closest_to, - compareAsc: compare_asc, - compareDesc: compare_desc, - differenceInCalendarDays: difference_in_calendar_days, - differenceInCalendarISOWeeks: difference_in_calendar_iso_weeks, - differenceInCalendarISOYears: difference_in_calendar_iso_years, - differenceInCalendarMonths: difference_in_calendar_months, - differenceInCalendarQuarters: difference_in_calendar_quarters, - differenceInCalendarWeeks: difference_in_calendar_weeks, - differenceInCalendarYears: difference_in_calendar_years, - differenceInDays: difference_in_days, - differenceInHours: difference_in_hours, - differenceInISOYears: difference_in_iso_years, - differenceInMilliseconds: difference_in_milliseconds, - differenceInMinutes: difference_in_minutes, - differenceInMonths: difference_in_months, - differenceInQuarters: difference_in_quarters, - differenceInSeconds: difference_in_seconds, - differenceInWeeks: difference_in_weeks, - differenceInYears: difference_in_years, - distanceInWords: distance_in_words, - distanceInWordsStrict: distance_in_words_strict, - distanceInWordsToNow: distance_in_words_to_now, - eachDay: each_day, - endOfDay: end_of_day, - endOfHour: end_of_hour, - endOfISOWeek: end_of_iso_week, - endOfISOYear: end_of_iso_year, - endOfMinute: end_of_minute, - endOfMonth: end_of_month, - endOfQuarter: end_of_quarter, - endOfSecond: end_of_second, - endOfToday: end_of_today, - endOfTomorrow: end_of_tomorrow, - endOfWeek: end_of_week, - endOfYear: end_of_year, - endOfYesterday: end_of_yesterday, - format: format_1, - getDate: get_date, - getDay: get_day, - getDayOfYear: get_day_of_year, - getDaysInMonth: get_days_in_month, - getDaysInYear: get_days_in_year, - getHours: get_hours, - getISODay: get_iso_day, - getISOWeek: get_iso_week, - getISOWeeksInYear: get_iso_weeks_in_year, - getISOYear: get_iso_year, - getMilliseconds: get_milliseconds, - getMinutes: get_minutes, - getMonth: get_month, - getOverlappingDaysInRanges: get_overlapping_days_in_ranges, - getQuarter: get_quarter, - getSeconds: get_seconds, - getTime: get_time, - getYear: get_year, - isAfter: is_after, - isBefore: is_before, - isDate: is_date, - isEqual: is_equal, - isFirstDayOfMonth: is_first_day_of_month, - isFriday: is_friday, - isFuture: is_future, - isLastDayOfMonth: is_last_day_of_month, - isLeapYear: is_leap_year, - isMonday: is_monday, - isPast: is_past, - isSameDay: is_same_day, - isSameHour: is_same_hour, - isSameISOWeek: is_same_iso_week, - isSameISOYear: is_same_iso_year, - isSameMinute: is_same_minute, - isSameMonth: is_same_month, - isSameQuarter: is_same_quarter, - isSameSecond: is_same_second, - isSameWeek: is_same_week, - isSameYear: is_same_year, - isSaturday: is_saturday, - isSunday: is_sunday, - isThisHour: is_this_hour, - isThisISOWeek: is_this_iso_week, - isThisISOYear: is_this_iso_year, - isThisMinute: is_this_minute, - isThisMonth: is_this_month, - isThisQuarter: is_this_quarter, - isThisSecond: is_this_second, - isThisWeek: is_this_week, - isThisYear: is_this_year, - isThursday: is_thursday, - isToday: is_today, - isTomorrow: is_tomorrow, - isTuesday: is_tuesday, - isValid: is_valid, - isWednesday: is_wednesday, - isWeekend: is_weekend, - isWithinRange: is_within_range, - isYesterday: is_yesterday, - lastDayOfISOWeek: last_day_of_iso_week, - lastDayOfISOYear: last_day_of_iso_year, - lastDayOfMonth: last_day_of_month, - lastDayOfQuarter: last_day_of_quarter, - lastDayOfWeek: last_day_of_week, - lastDayOfYear: last_day_of_year, - max: max_1, - min: min_1, - parse: parse_1, - setDate: set_date, - setDay: set_day, - setDayOfYear: set_day_of_year, - setHours: set_hours, - setISODay: set_iso_day, - setISOWeek: set_iso_week, - setISOYear: set_iso_year, - setMilliseconds: set_milliseconds, - setMinutes: set_minutes, - setMonth: set_month, - setQuarter: set_quarter, - setSeconds: set_seconds, - setYear: set_year, - startOfDay: start_of_day, - startOfHour: start_of_hour, - startOfISOWeek: start_of_iso_week, - startOfISOYear: start_of_iso_year, - startOfMinute: start_of_minute, - startOfMonth: start_of_month, - startOfQuarter: start_of_quarter, - startOfSecond: start_of_second, - startOfToday: start_of_today, - startOfTomorrow: start_of_tomorrow, - startOfWeek: start_of_week, - startOfYear: start_of_year, - startOfYesterday: start_of_yesterday, - subDays: sub_days, - subHours: sub_hours, - subISOYears: sub_iso_years, - subMilliseconds: sub_milliseconds, - subMinutes: sub_minutes, - subMonths: sub_months, - subQuarters: sub_quarters, - subSeconds: sub_seconds, - subWeeks: sub_weeks, - subYears: sub_years - }; - - const user = "user"; - - const date$2 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo$2 = `Sunnyvale ${user} ${date$2}`; - - const date$1 = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo$1 = `@foo/lib/a ${date$1}`; - - const date = dateFns.format(new Date(2019, 4, 7), 'MMMM D, YYYY'); - const foo = `@foo/lib/a/a/a ${date}`; - - const fum = 'Wonderland'; - - var hello = 'Hello'; - - const name = 'Alice'; - - const json_key = "json_value"; - - console.log( - `${hello}, ${name} in ${fum} ${foo$2} ${foo$1} ${foo} ${far_a} ${far_a_b_c} ${json_key}`); - - // Test for sequences = false - class A { - a() { - return document.a; - } - } - function inline_me() { - return 'abc'; - } - console.error(new A().a(), inline_me(), some_global_var.thing); - - exports.A = A; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); -//# sourceMappingURL=bundle.umd.js.map
diff --git a/packages/rollup/test/integration/rollup.config.js b/packages/rollup/test/integration/rollup.config.js deleted file mode 100644 index fa9041d..0000000 --- a/packages/rollup/test/integration/rollup.config.js +++ /dev/null
@@ -1,67 +0,0 @@ -import commonjs from '@rollup/plugin-commonjs'; -import json from '@rollup/plugin-json'; -import nodeResolve from '@rollup/plugin-node-resolve'; - -/** -* The status files are expected to look like -* BUILD_SCM_HASH 83c699db39cfd74526cdf9bebb75aa6f122908bb -* BUILD_SCM_LOCAL_CHANGES true -* STABLE_BUILD_SCM_VERSION 6.0.0-beta.6+12.sha-83c699d.with-local-changes -* BUILD_TIMESTAMP 1520021990506 -* -* Parsing regex is created based on Bazel's documentation describing the status file schema: -* The key names can be anything but they may only use upper case letters and underscores. The -* first space after the key name separates it from the value. The value is the rest of the line -* (including additional whitespaces). -* -* @param {string} p the path to the status file -* @returns a two-dimensional array of key/value pairs -*/ -function parseStatusFile(p) { - if (!p) return []; - const results = {}; - const statusFile = require('fs').readFileSync(p, {encoding: 'utf-8'}); - for (const match of `\n${statusFile}`.matchAll(/^([A-Z_]+) (.*)/gm)) { - // Lines which go unmatched define an index value of `0` and should be skipped. - if (match.index === 0) { - continue; - } - results[match[1]] = match[2]; - } - return results; -} - -// Parse the stamp file produced by Bazel from the version control system -let version = '<unknown>'; - -const statuses = parseStatusFile(bazel_version_file); -// Don't assume BUILD_SCM_VERSION exists -if (statuses['BUILD_SCM_VERSION']) { - version = 'v' + statuses['BUILD_SCM_VERSION']; - if (DEBUG) { - version += '_debug'; - } -} - -let banner = `/** - * @license A dummy license banner that goes at the top of the file. - * This is version ${version} - */ -`; - - -module.exports = { - onwarn: (warning) => { - // Always fail on warnings, assuming we don't know which are harmless. - // We can add exclusions here based on warning.code, if we discover some - // types of warning should always be ignored under bazel. - throw new Error(warning.message); - }, - external: ['some_global_var'], - output: {name: 'bundle', banner, globals: {some_global_var: 'runtime_name_of_global_var'}}, - plugins: [ - nodeResolve(), - commonjs(), - json({preferConst: true}), - ], -};
diff --git a/packages/rollup/test/integration/sha256.js b/packages/rollup/test/integration/sha256.js deleted file mode 100644 index 2c68af6..0000000 --- a/packages/rollup/test/integration/sha256.js +++ /dev/null
@@ -1,5 +0,0 @@ -const crypto = require('crypto'); -const fs = require('fs'); -const sha256sum = crypto.createHash('sha256'); -sha256sum.update(fs.readFileSync(process.argv[2], {encoding: 'utf-8'})); -fs.writeFileSync(process.argv[3], sha256sum.digest('hex'));
diff --git a/packages/rollup/test/integration/some.json b/packages/rollup/test/integration/some.json deleted file mode 100644 index 813ac25..0000000 --- a/packages/rollup/test/integration/some.json +++ /dev/null
@@ -1,3 +0,0 @@ -{ - "json_key": "json_value" -}
diff --git a/packages/rollup/test/multi_linker/BUILD.bazel b/packages/rollup/test/multi_linker/BUILD.bazel deleted file mode 100644 index b1ec31e..0000000 --- a/packages/rollup/test/multi_linker/BUILD.bazel +++ /dev/null
@@ -1,33 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test") -load("//packages/rollup:index.bzl", "rollup_bundle") -load("//packages/typescript:index.bzl", "ts_project") - -ts_project( - name = "tsconfig", - srcs = glob(["*.ts"]), - deps = ["@rollup_test_multi_linker_deps//@types"], -) - -# Intentionally test with only generated files by transpiling with ts_project -# to test multi-linker build action with no source inputs. -# NB: rollup.config.js is used to generated "_{name}.rollup_config.js" in output -# tree. Only the generated config is a input to the rollup build action. -rollup_bundle( - name = "bundle", - config_file = "rollup.config.js", - entry_point = "main.js", - sourcemap = "hidden", - deps = [ - "tsconfig", - "@rollup_test_multi_linker_deps//@rollup/plugin-commonjs", - "@rollup_test_multi_linker_deps//@rollup/plugin-node-resolve", - ], -) - -generated_file_test( - name = "test", - src = "golden.js_", - generated = "bundle.js", - # fails in some non-trivial way on Windows; not particularly important to Windows coverage here - tags = ["fix-windows"], -)
diff --git a/packages/rollup/test/multi_linker/golden.js_ b/packages/rollup/test/multi_linker/golden.js_ deleted file mode 100644 index 7278d1f..0000000 --- a/packages/rollup/test/multi_linker/golden.js_ +++ /dev/null
@@ -1,22 +0,0 @@ -function createCommonjsModule(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function (path, base) { - return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); - } - }, fn(module, module.exports), module.exports; -} - -function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); -} - -var lib = createCommonjsModule(function (module, exports) { -exports.__esModule = true; -exports.key = void 0; -exports.key = 'rollup'; -}); - -var key = lib.key; -console.log(key);
diff --git a/packages/rollup/test/multi_linker/lib.ts b/packages/rollup/test/multi_linker/lib.ts deleted file mode 100644 index 294f9fa..0000000 --- a/packages/rollup/test/multi_linker/lib.ts +++ /dev/null
@@ -1 +0,0 @@ -export const key: string = 'rollup'; \ No newline at end of file
diff --git a/packages/rollup/test/multi_linker/main.ts b/packages/rollup/test/multi_linker/main.ts deleted file mode 100644 index 1b00e22..0000000 --- a/packages/rollup/test/multi_linker/main.ts +++ /dev/null
@@ -1,2 +0,0 @@ -const key = require('./lib').key; -console.log(key); \ No newline at end of file
diff --git a/packages/rollup/test/multi_linker/package.json b/packages/rollup/test/multi_linker/package.json deleted file mode 100644 index 484b5cc..0000000 --- a/packages/rollup/test/multi_linker/package.json +++ /dev/null
@@ -1,7 +0,0 @@ -{ - "devDependencies": { - "@types/node": "14.14.26", - "@rollup/plugin-commonjs": "14.0.0", - "@rollup/plugin-node-resolve": "8.4.0" - } -}
diff --git a/packages/rollup/test/multi_linker/rollup.config.js b/packages/rollup/test/multi_linker/rollup.config.js deleted file mode 100644 index b7ab78d..0000000 --- a/packages/rollup/test/multi_linker/rollup.config.js +++ /dev/null
@@ -1,9 +0,0 @@ -const {nodeResolve} = require('@rollup/plugin-node-resolve') -const commonjs = require('@rollup/plugin-commonjs') - -module.exports = { - plugins: [ - nodeResolve(), - commonjs(), - ], -}
diff --git a/packages/rollup/test/multi_linker/tsconfig.json b/packages/rollup/test/multi_linker/tsconfig.json deleted file mode 100644 index cbe2c10..0000000 --- a/packages/rollup/test/multi_linker/tsconfig.json +++ /dev/null
@@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "types": ["node"] - } -} \ No newline at end of file
diff --git a/packages/rollup/test/multi_linker/yarn.lock b/packages/rollup/test/multi_linker/yarn.lock deleted file mode 100644 index a896fd1..0000000 --- a/packages/rollup/test/multi_linker/yarn.lock +++ /dev/null
@@ -1,218 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@rollup/plugin-commonjs@14.0.0": - version "14.0.0" - resolved "https://registry.yarnpkg.com/@rollup/plugin-commonjs/-/plugin-commonjs-14.0.0.tgz#4285f9ec2db686a31129e5a2b415c94aa1f836f0" - integrity sha512-+PSmD9ePwTAeU106i9FRdc+Zb3XUWyW26mo5Atr2mk82hor8+nPwkztEjFo8/B1fJKfaQDg9aM2bzQkjhi7zOw== - dependencies: - "@rollup/pluginutils" "^3.0.8" - commondir "^1.0.1" - estree-walker "^1.0.1" - glob "^7.1.2" - is-reference "^1.1.2" - magic-string "^0.25.2" - resolve "^1.11.0" - -"@rollup/plugin-node-resolve@8.4.0": - version "8.4.0" - resolved "https://registry.yarnpkg.com/@rollup/plugin-node-resolve/-/plugin-node-resolve-8.4.0.tgz#261d79a680e9dc3d86761c14462f24126ba83575" - integrity sha512-LFqKdRLn0ShtQyf6SBYO69bGE1upV6wUhBX0vFOUnLAyzx5cwp8svA0eHUnu8+YU57XOkrMtfG63QOpQx25pHQ== - dependencies: - "@rollup/pluginutils" "^3.1.0" - "@types/resolve" "1.17.1" - builtin-modules "^3.1.0" - deep-freeze "^0.0.1" - deepmerge "^4.2.2" - is-module "^1.0.0" - resolve "^1.17.0" - -"@rollup/pluginutils@^3.0.8", "@rollup/pluginutils@^3.1.0": - version "3.1.0" - resolved "https://registry.yarnpkg.com/@rollup/pluginutils/-/pluginutils-3.1.0.tgz#706b4524ee6dc8b103b3c995533e5ad680c02b9b" - integrity sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg== - dependencies: - "@types/estree" "0.0.39" - estree-walker "^1.0.1" - picomatch "^2.2.2" - -"@types/estree@*": - version "0.0.46" - resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.46.tgz#0fb6bfbbeabd7a30880504993369c4bf1deab1fe" - integrity sha512-laIjwTQaD+5DukBZaygQ79K1Z0jb1bPEMRrkXSLjtCcZm+abyp5YbrqpSLzD42FwWW6gK/aS4NYpJ804nG2brg== - -"@types/estree@0.0.39": - version "0.0.39" - resolved "https://registry.yarnpkg.com/@types/estree/-/estree-0.0.39.tgz#e177e699ee1b8c22d23174caaa7422644389509f" - integrity sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw== - -"@types/node@*", "@types/node@14.14.26": - version "14.14.26" - resolved "https://registry.yarnpkg.com/@types/node/-/node-14.14.26.tgz#e40df24c957568f350cca04e63bfb1e1556d1cbf" - integrity sha512-skWxepWOs+VArEBWd2S/VR3wUavioIIx9/HzW+UJiIjtwa6+kNXdsOeq7FfxDXf56hIcL0ieo2brwMgBJ1+lhw== - -"@types/resolve@1.17.1": - version "1.17.1" - resolved "https://registry.yarnpkg.com/@types/resolve/-/resolve-1.17.1.tgz#3afd6ad8967c77e4376c598a82ddd58f46ec45d6" - integrity sha512-yy7HuzQhj0dhGpD8RLXSZWEkLsV9ibvxvi6EiJ3bkqLAO1RGo0WbkWQiwpRlSFymTJRz0d3k5LM3kkx8ArDbLw== - dependencies: - "@types/node" "*" - -balanced-match@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" - integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= - -brace-expansion@^1.1.7: - version "1.1.11" - resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" - integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== - dependencies: - balanced-match "^1.0.0" - concat-map "0.0.1" - -builtin-modules@^3.1.0: - version "3.2.0" - resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-3.2.0.tgz#45d5db99e7ee5e6bc4f362e008bf917ab5049887" - integrity sha512-lGzLKcioL90C7wMczpkY0n/oART3MbBa8R9OFGE1rJxoVI86u4WAGfEk8Wjv10eKSyTHVGkSo3bvBylCEtk7LA== - -commondir@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/commondir/-/commondir-1.0.1.tgz#ddd800da0c66127393cca5950ea968a3aaf1253b" - integrity sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs= - -concat-map@0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" - integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= - -deep-freeze@^0.0.1: - version "0.0.1" - resolved "https://registry.yarnpkg.com/deep-freeze/-/deep-freeze-0.0.1.tgz#3a0b0005de18672819dfd38cd31f91179c893e84" - integrity sha1-OgsABd4YZygZ39OM0x+RF5yJPoQ= - -deepmerge@^4.2.2: - version "4.2.2" - resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.2.2.tgz#44d2ea3679b8f4d4ffba33f03d865fc1e7bf4955" - integrity sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg== - -estree-walker@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/estree-walker/-/estree-walker-1.0.1.tgz#31bc5d612c96b704106b477e6dd5d8aa138cb700" - integrity sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg== - -fs.realpath@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" - integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= - -function-bind@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" - integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== - -glob@^7.1.2: - version "7.1.6" - resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" - integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== - dependencies: - fs.realpath "^1.0.0" - inflight "^1.0.4" - inherits "2" - minimatch "^3.0.4" - once "^1.3.0" - path-is-absolute "^1.0.0" - -has@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796" - integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw== - dependencies: - function-bind "^1.1.1" - -inflight@^1.0.4: - version "1.0.6" - resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" - integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= - dependencies: - once "^1.3.0" - wrappy "1" - -inherits@2: - version "2.0.4" - resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" - integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== - -is-core-module@^2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.2.0.tgz#97037ef3d52224d85163f5597b2b63d9afed981a" - integrity sha512-XRAfAdyyY5F5cOXn7hYQDqh2Xmii+DEfIcQGxK/uNwMHhIkPWO0g8msXcbzLe+MpGoR951MlqM/2iIlU4vKDdQ== - dependencies: - has "^1.0.3" - -is-module@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-module/-/is-module-1.0.0.tgz#3258fb69f78c14d5b815d664336b4cffb6441591" - integrity sha1-Mlj7afeMFNW4FdZkM2tM/7ZEFZE= - -is-reference@^1.1.2: - version "1.2.1" - resolved "https://registry.yarnpkg.com/is-reference/-/is-reference-1.2.1.tgz#8b2dac0b371f4bc994fdeaba9eb542d03002d0b7" - integrity sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ== - dependencies: - "@types/estree" "*" - -magic-string@^0.25.2: - version "0.25.7" - resolved "https://registry.yarnpkg.com/magic-string/-/magic-string-0.25.7.tgz#3f497d6fd34c669c6798dcb821f2ef31f5445051" - integrity sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA== - dependencies: - sourcemap-codec "^1.4.4" - -minimatch@^3.0.4: - version "3.0.4" - resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" - integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== - dependencies: - brace-expansion "^1.1.7" - -once@^1.3.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" - integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= - dependencies: - wrappy "1" - -path-is-absolute@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" - integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= - -path-parse@^1.0.6: - version "1.0.6" - resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c" - integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw== - -picomatch@^2.2.2: - version "2.2.2" - resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad" - integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg== - -resolve@^1.11.0, resolve@^1.17.0: - version "1.20.0" - resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.20.0.tgz#629a013fb3f70755d6f0b7935cc1c2c5378b1975" - integrity sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A== - dependencies: - is-core-module "^2.2.0" - path-parse "^1.0.6" - -sourcemap-codec@^1.4.4: - version "1.4.8" - resolved "https://registry.yarnpkg.com/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz#ea804bd94857402e6992d05a38ef1ae35a9ab4c4" - integrity sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA== - -wrappy@1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" - integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=
diff --git a/packages/rollup/test/multiple_entry_points/BUILD.bazel b/packages/rollup/test/multiple_entry_points/BUILD.bazel deleted file mode 100644 index 62af519..0000000 --- a/packages/rollup/test/multiple_entry_points/BUILD.bazel +++ /dev/null
@@ -1,11 +0,0 @@ -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "chunks", - entry_points = { - "entry1.js": "one", - "entry2.js": "two", - }, - output_dir = True, - supports_workers = True, -)
diff --git a/packages/rollup/test/multiple_entry_points/entry1.js b/packages/rollup/test/multiple_entry_points/entry1.js deleted file mode 100644 index 485be7d..0000000 --- a/packages/rollup/test/multiple_entry_points/entry1.js +++ /dev/null
@@ -1,3 +0,0 @@ -const hello1 = document.createElement('span'); -hello1.innerText = 'hello from entry point 1'; -window.document.body.appendChild(hello1); \ No newline at end of file
diff --git a/packages/rollup/test/multiple_entry_points/entry2.js b/packages/rollup/test/multiple_entry_points/entry2.js deleted file mode 100644 index 8290056..0000000 --- a/packages/rollup/test/multiple_entry_points/entry2.js +++ /dev/null
@@ -1,3 +0,0 @@ -const hello2 = document.createElement('span'); -hello2.innerText = 'hello from entry point 2'; -window.document.body.appendChild(hello1); \ No newline at end of file
diff --git a/packages/rollup/test/multiple_entry_points/spec.js b/packages/rollup/test/multiple_entry_points/spec.js deleted file mode 100644 index e4b4549..0000000 --- a/packages/rollup/test/multiple_entry_points/spec.js +++ /dev/null
@@ -1,10 +0,0 @@ -const fs = require('fs'); -const runfiles = require(process.env['BAZEL_NODE_RUNFILES_HELPER']); - -describe('rollup multiple entry points', () => { - it('should produce a chunk for each entry point', () => { - const chunks = runfiles.resolvePackageRelative('chunks'); - expect(fs.existsSync(chunks + '/one.js')).toBeTruthy(); - expect(fs.existsSync(chunks + '/two.js')).toBeTruthy(); - }); -});
diff --git a/packages/rollup/test/plugins/BUILD.bazel b/packages/rollup/test/plugins/BUILD.bazel deleted file mode 100644 index b632b36..0000000 --- a/packages/rollup/test/plugins/BUILD.bazel +++ /dev/null
@@ -1,18 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test") -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "plugins", - srcs = ["some.json"], - config_file = "rollup.config.js", - entry_point = "input.js", - sourcemap = "false", - supports_workers = True, - deps = ["@npm//@rollup/plugin-json"], -) - -generated_file_test( - name = "test", - src = "golden.js_", - generated = "plugins.js", -)
diff --git a/packages/rollup/test/plugins/golden.js_ b/packages/rollup/test/plugins/golden.js_ deleted file mode 100644 index fe2887c..0000000 --- a/packages/rollup/test/plugins/golden.js_ +++ /dev/null
@@ -1,3 +0,0 @@ -const json_key = "json_value"; - -console.log(json_key);
diff --git a/packages/rollup/test/plugins/input.js b/packages/rollup/test/plugins/input.js deleted file mode 100644 index 37b76ce..0000000 --- a/packages/rollup/test/plugins/input.js +++ /dev/null
@@ -1,3 +0,0 @@ -import {json_key} from './some.json'; - -console.log(json_key);
diff --git a/packages/rollup/test/plugins/rollup.config.js b/packages/rollup/test/plugins/rollup.config.js deleted file mode 100644 index 883a8ea..0000000 --- a/packages/rollup/test/plugins/rollup.config.js +++ /dev/null
@@ -1,7 +0,0 @@ -import json from '@rollup/plugin-json'; - -module.exports = { - plugins: [ - json({preferConst: true}), - ], -};
diff --git a/packages/rollup/test/plugins/some.json b/packages/rollup/test/plugins/some.json deleted file mode 100644 index 813ac25..0000000 --- a/packages/rollup/test/plugins/some.json +++ /dev/null
@@ -1,3 +0,0 @@ -{ - "json_key": "json_value" -}
diff --git a/packages/rollup/test/silent/BUILD.bazel b/packages/rollup/test/silent/BUILD.bazel deleted file mode 100644 index 143a5be..0000000 --- a/packages/rollup/test/silent/BUILD.bazel +++ /dev/null
@@ -1,15 +0,0 @@ -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "silent", - srcs = ["input.js"], - entry_points = {"input.js": "silent"}, - silent = True, -) - -rollup_bundle( - name = "silent_on_success", - srcs = ["input.js"], - entry_points = {"input.js": "silent_on_success"}, - silent_on_success = True, -)
diff --git a/packages/rollup/test/silent/input.js b/packages/rollup/test/silent/input.js deleted file mode 100644 index 702f428..0000000 --- a/packages/rollup/test/silent/input.js +++ /dev/null
@@ -1 +0,0 @@ -console.log("hello");
diff --git a/packages/rollup/test/sourcemaps/BUILD.bazel b/packages/rollup/test/sourcemaps/BUILD.bazel deleted file mode 100644 index c20de3e..0000000 --- a/packages/rollup/test/sourcemaps/BUILD.bazel +++ /dev/null
@@ -1,15 +0,0 @@ -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "bundle", - srcs = ["s.js"], - # Test existance of args attribute - args = [ - "--environment", - "FOO,BAR:baz", - ], - # Use the desugared form to assert that it works - entry_points = {"input.js": "bundle"}, - sourcemap = "true", - supports_workers = True, -)
diff --git a/packages/rollup/test/sourcemaps/input.js b/packages/rollup/test/sourcemaps/input.js deleted file mode 100644 index 90d4f80..0000000 --- a/packages/rollup/test/sourcemaps/input.js +++ /dev/null
@@ -1,2 +0,0 @@ -import {s} from './s' -console.error(s);
diff --git a/packages/rollup/test/sourcemaps/s.js b/packages/rollup/test/sourcemaps/s.js deleted file mode 100644 index 4efa860..0000000 --- a/packages/rollup/test/sourcemaps/s.js +++ /dev/null
@@ -1 +0,0 @@ -export const s = 'hello'; \ No newline at end of file
diff --git a/packages/rollup/test/sourcemaps/spec.js b/packages/rollup/test/sourcemaps/spec.js deleted file mode 100644 index 091cb57..0000000 --- a/packages/rollup/test/sourcemaps/spec.js +++ /dev/null
@@ -1,20 +0,0 @@ -const fs = require('fs'); -const sm = require('source-map'); -const runfiles = require(process.env['BAZEL_NODE_RUNFILES_HELPER']); - -describe('rollup sourcemap handling', () => { - it('should produce a sourcemap output', async () => { - const file = runfiles.resolvePackageRelative('bundle.js.map'); - const rawSourceMap = JSON.parse(fs.readFileSync(file, 'utf-8')); - await sm.SourceMapConsumer.with(rawSourceMap, null, consumer => { - const pos = consumer.originalPositionFor({line: 1, column: 12}); - // This doesn't work because the output dir is different from input - // so it actually starts with a bunch of '/../..' - // expect(pos.source).toBe('s.js'); - - expect(pos.source.endsWith('s.js')).toBeTruthy(); - expect(pos.line).toBe(1); - expect(pos.column).toBe(17); - }); - }); -});
diff --git a/packages/rollup/test/ts_project/BUILD.bazel b/packages/rollup/test/ts_project/BUILD.bazel deleted file mode 100644 index 1eb852d..0000000 --- a/packages/rollup/test/ts_project/BUILD.bazel +++ /dev/null
@@ -1,35 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") -load("//:index.bzl", "generated_file_test") -load("//packages/rollup:index.bzl", "rollup_bundle") - -exports_files(["tsconfig.json"]) - -copy_to_bin( - name = "main-bin", - srcs = ["main.js"], -) - -rollup_bundle( - name = "bundle", - entry_point = "main-bin", - format = "esm", - deps = [ - "//packages/rollup/test/ts_project/module-dynamic", - "//packages/rollup/test/ts_project/module-one", - "//packages/rollup/test/ts_project/module-two", - "//packages/rollup/test/ts_project/relative-module", - ], -) - -genrule( - name = "strip_bundle_comments", - srcs = ["bundle.js"], - outs = ["bundle.stripped.js"], - cmd = "cat $(location :bundle.js) | sed \"s#//.*##\" > $@", -) - -generated_file_test( - name = "bundle_test", - src = "bundle.golden.txt", - generated = ":bundle.stripped.js", -)
diff --git a/packages/rollup/test/ts_project/bundle.golden.txt b/packages/rollup/test/ts_project/bundle.golden.txt deleted file mode 100644 index efe3cfa..0000000 --- a/packages/rollup/test/ts_project/bundle.golden.txt +++ /dev/null
@@ -1,12 +0,0 @@ -import { getId as getId$3 } from '@typescript/module-dynamic'; -import { getId as getId$1 } from '@typescript/module-one'; -import { getId as getId$2 } from '@typescript/module-two'; - -const getId = () => 'relative-module'; - -const ID = `Full ID: ${getId$1()} - ${getId$2()} - ${getId$3()} - ${getId()}`; - -console.log(ID); - -export { ID }; -
diff --git a/packages/rollup/test/ts_project/main.js b/packages/rollup/test/ts_project/main.js deleted file mode 100644 index f8f27dc..0000000 --- a/packages/rollup/test/ts_project/main.js +++ /dev/null
@@ -1,9 +0,0 @@ -import {getId as mdyn} from '@typescript/module-dynamic'; -import {getId as m1Id} from '@typescript/module-one'; -import {getId as m2Id} from '@typescript/module-two'; - -import {getId as mRelId} from './relative-module/lib'; - -export const ID = `Full ID: ${m1Id()} - ${m2Id()} - ${mdyn()} - ${mRelId()}`; - -console.log(ID);
diff --git a/packages/rollup/test/ts_project/module-dynamic/BUILD.bazel b/packages/rollup/test/ts_project/module-dynamic/BUILD.bazel deleted file mode 100644 index ac84944..0000000 --- a/packages/rollup/test/ts_project/module-dynamic/BUILD.bazel +++ /dev/null
@@ -1,19 +0,0 @@ -load("//internal/js_library:js_library.bzl", "js_library") -load("//packages/typescript:index.bzl", "ts_project") - -package(default_visibility = ["//packages/rollup/test:__subpackages__"]) - -ts_project( - name = "compile", - srcs = [":index.ts"], - declaration = True, - extends = "//packages/rollup/test/ts_project:tsconfig.json", - tsconfig = {}, -) - -js_library( - name = "module-dynamic", - package_name = "@typescript/module-dynamic", - srcs = [":random-file.css"], - deps = [":compile"], -)
diff --git a/packages/rollup/test/ts_project/module-dynamic/index.ts b/packages/rollup/test/ts_project/module-dynamic/index.ts deleted file mode 100644 index b6fec9e..0000000 --- a/packages/rollup/test/ts_project/module-dynamic/index.ts +++ /dev/null
@@ -1 +0,0 @@ -export const getId = () => 'dynamic-id';
diff --git a/packages/rollup/test/ts_project/module-dynamic/random-file.css b/packages/rollup/test/ts_project/module-dynamic/random-file.css deleted file mode 100644 index da0e4c7..0000000 --- a/packages/rollup/test/ts_project/module-dynamic/random-file.css +++ /dev/null
@@ -1,3 +0,0 @@ -.some-random { - font-family: 'Comic Sans'; -}
diff --git a/packages/rollup/test/ts_project/module-one/BUILD.bazel b/packages/rollup/test/ts_project/module-one/BUILD.bazel deleted file mode 100644 index f04014f..0000000 --- a/packages/rollup/test/ts_project/module-one/BUILD.bazel +++ /dev/null
@@ -1,18 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "js_library") -load("//packages/typescript:index.bzl", "ts_project") - -package(default_visibility = ["//packages/rollup/test:__subpackages__"]) - -ts_project( - name = "project", - srcs = [":index.ts"], - declaration = True, - extends = "//packages/rollup/test/ts_project:tsconfig.json", - tsconfig = {}, -) - -js_library( - name = "module-one", - package_name = "@typescript/module-one", - deps = [":project"], -)
diff --git a/packages/rollup/test/ts_project/module-one/index.ts b/packages/rollup/test/ts_project/module-one/index.ts deleted file mode 100644 index be8c740..0000000 --- a/packages/rollup/test/ts_project/module-one/index.ts +++ /dev/null
@@ -1 +0,0 @@ -export const getId = () => 'module-one';
diff --git a/packages/rollup/test/ts_project/module-two/BUILD.bazel b/packages/rollup/test/ts_project/module-two/BUILD.bazel deleted file mode 100644 index a163211..0000000 --- a/packages/rollup/test/ts_project/module-two/BUILD.bazel +++ /dev/null
@@ -1,18 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "js_library") -load("//packages/typescript:index.bzl", "ts_project") - -package(default_visibility = ["//packages/rollup/test:__subpackages__"]) - -ts_project( - name = "project", - srcs = [":index.ts"], - declaration = True, - extends = "//packages/rollup/test/ts_project:tsconfig.json", - tsconfig = {}, -) - -js_library( - name = "module-two", - package_name = "@typescript/module-two", - deps = [":project"], -)
diff --git a/packages/rollup/test/ts_project/module-two/index.ts b/packages/rollup/test/ts_project/module-two/index.ts deleted file mode 100644 index 4fa9280..0000000 --- a/packages/rollup/test/ts_project/module-two/index.ts +++ /dev/null
@@ -1 +0,0 @@ -export const getId = () => 'module-two';
diff --git a/packages/rollup/test/ts_project/relative-module/BUILD.bazel b/packages/rollup/test/ts_project/relative-module/BUILD.bazel deleted file mode 100644 index 51e08ca..0000000 --- a/packages/rollup/test/ts_project/relative-module/BUILD.bazel +++ /dev/null
@@ -1,11 +0,0 @@ -load("//packages/typescript:index.bzl", "ts_project") - -package(default_visibility = ["//packages/rollup/test:__subpackages__"]) - -ts_project( - name = "relative-module", - srcs = ["lib.ts"], - declaration = True, - extends = "//packages/rollup/test/ts_project:tsconfig.json", - tsconfig = {}, -)
diff --git a/packages/rollup/test/ts_project/relative-module/lib.ts b/packages/rollup/test/ts_project/relative-module/lib.ts deleted file mode 100644 index 61fbbee..0000000 --- a/packages/rollup/test/ts_project/relative-module/lib.ts +++ /dev/null
@@ -1 +0,0 @@ -export const getId = () => 'relative-module';
diff --git a/packages/rollup/test/ts_project/rollup.config.js b/packages/rollup/test/ts_project/rollup.config.js deleted file mode 100644 index 6806c98..0000000 --- a/packages/rollup/test/ts_project/rollup.config.js +++ /dev/null
@@ -1,13 +0,0 @@ -import nodeResolve from '@rollup/plugin-node-resolve'; - -module.exports = { - onwarn: (warning) => { - // Always fail on warnings, assuming we don't know which are harmless. - // We can add exclusions here based on warning.code, if we discover some - // types of warning should always be ignored under bazel. - throw new Error(warning.message); - }, - plugins: [ - nodeResolve(), - ], -};
diff --git a/packages/rollup/test/ts_project/tsconfig.json b/packages/rollup/test/ts_project/tsconfig.json deleted file mode 100644 index 1b1faba..0000000 --- a/packages/rollup/test/ts_project/tsconfig.json +++ /dev/null
@@ -1,22 +0,0 @@ -{ - "compilerOptions": { - "target": "es6", - "declaration": true, - "module": "esnext", - "moduleResolution": "node", - "esModuleInterop": true, - "skipLibCheck": true, - - // Help TypeScript locate the a.d.ts file from previous compilation. Needed when running in a sandbox or remote. - "rootDirs": [ - ".", - "../../../../bazel-out/darwin-fastbuild/bin/packages/rollup/test/ts_project", - "../../../../bazel-out/darwin_arm64-fastbuild/bin/packages/rollup/test/ts_project", - "../../../../bazel-out/k8-fastbuild/bin/packages/rollup/test/ts_project", - "../../../../bazel-out/x64_windows-fastbuild/bin/packages/rollup/test/ts_project", - "../../../../bazel-out/darwin-dbg/bin/packages/rollup/test/ts_project", - "../../../../bazel-out/k8-dbg/bin/packages/rollup/test/ts_project", - "../../../../bazel-out/x64_windows-dbg/bin/packages/rollup/test/ts_project", - ], - } -}
diff --git a/packages/rollup/test/version_stamp/BUILD.bazel b/packages/rollup/test/version_stamp/BUILD.bazel deleted file mode 100644 index c698449..0000000 --- a/packages/rollup/test/version_stamp/BUILD.bazel +++ /dev/null
@@ -1,19 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test") -load("//packages/rollup:index.bzl", "rollup_bundle") - -rollup_bundle( - name = "version_stamp", - config_file = "rollup.config.js", - entry_point = "input.js", - sourcemap = "false", - stamp = "@rules_nodejs//nodejs/stamp:always", - supports_workers = True, -) - -generated_file_test( - name = "test", - src = "golden.js_", - # Leave off the ".js" extension to test that it's the default output - generated = "version_stamp", - src_dbg = "golden_debug.js_", -)
diff --git a/packages/rollup/test/version_stamp/golden.js_ b/packages/rollup/test/version_stamp/golden.js_ deleted file mode 100644 index 94076a9..0000000 --- a/packages/rollup/test/version_stamp/golden.js_ +++ /dev/null
@@ -1,7 +0,0 @@ -/** - * @license A dummy license banner that goes at the top of the file. - * This is version v1.2.3 - */ - -// License banner with version stamp will appear here -console.error('stamp');
diff --git a/packages/rollup/test/version_stamp/golden_debug.js_ b/packages/rollup/test/version_stamp/golden_debug.js_ deleted file mode 100644 index d336f78..0000000 --- a/packages/rollup/test/version_stamp/golden_debug.js_ +++ /dev/null
@@ -1,7 +0,0 @@ -/** - * @license A dummy license banner that goes at the top of the file. - * This is version v1.2.3_debug - */ - -// License banner with version stamp will appear here -console.error('stamp');
diff --git a/packages/rollup/test/version_stamp/input.js b/packages/rollup/test/version_stamp/input.js deleted file mode 100644 index ba39bcd..0000000 --- a/packages/rollup/test/version_stamp/input.js +++ /dev/null
@@ -1,2 +0,0 @@ -// License banner with version stamp will appear here -console.error('stamp');
diff --git a/packages/rollup/test/version_stamp/rollup.config.js b/packages/rollup/test/version_stamp/rollup.config.js deleted file mode 100644 index 735cc8f..0000000 --- a/packages/rollup/test/version_stamp/rollup.config.js +++ /dev/null
@@ -1,53 +0,0 @@ -/** -* The status files are expected to look like -* BUILD_SCM_HASH 83c699db39cfd74526cdf9bebb75aa6f122908bb -* BUILD_SCM_LOCAL_CHANGES true -* STABLE_BUILD_SCM_VERSION 6.0.0-beta.6+12.sha-83c699d.with-local-changes -* BUILD_TIMESTAMP 1520021990506 -* -* Parsing regex is created based on Bazel's documentation describing the status file schema: -* The key names can be anything but they may only use upper case letters and underscores. The -* first space after the key name separates it from the value. The value is the rest of the line -* (including additional whitespaces). -* -* @param {string} p the path to the status file -* @returns a two-dimensional array of key/value pairs -*/ -function parseStatusFile(p) { - if (!p) return []; - const results = {}; - const statusFile = require('fs').readFileSync(p, {encoding: 'utf-8'}); - for (const match of `\n${statusFile}`.matchAll(/^([A-Z_]+) (.*)/gm)) { - // Lines which go unmatched define an index value of `0` and should be skipped. - if (match.index === 0) { - continue; - } - results[match[1]] = match[2]; - } - return results; -} - -const DEBUG = process.env['COMPILATION_MODE'] === 'dbg'; - -// Parse the stamp file produced by Bazel from the version control system -let version = '<unknown>'; - -// This undefined variable will be replaced with the full path during the build. -const statuses = parseStatusFile(bazel_version_file); -// Don't assume BUILD_SCM_VERSION exists -if (statuses['BUILD_SCM_VERSION']) { - version = 'v' + statuses['BUILD_SCM_VERSION']; - if (DEBUG) { - version += '_debug'; - } -} - -const banner = `/** - * @license A dummy license banner that goes at the top of the file. - * This is version ${version} - */ -`; - -module.exports = { - output: {banner}, -};
diff --git a/packages/rollup/test/workspace_link/BUILD.bazel b/packages/rollup/test/workspace_link/BUILD.bazel deleted file mode 100644 index d794f80..0000000 --- a/packages/rollup/test/workspace_link/BUILD.bazel +++ /dev/null
@@ -1,23 +0,0 @@ -load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin") -load("//packages/rollup:index.bzl", "rollup_bundle") - -copy_to_bin( - name = "foo", - srcs = ["foo.js"], -) - -rollup_bundle( - name = "bundle", - srcs = [ - "bar.js", - "main.js", - ":foo", - ], - config_file = "rollup.config.js", - entry_point = "main.js", - link_workspace_root = True, - deps = [ - "@npm//@rollup/plugin-commonjs", - "@npm//@rollup/plugin-node-resolve", - ], -)
diff --git a/packages/rollup/test/workspace_link/bar.js b/packages/rollup/test/workspace_link/bar.js deleted file mode 100644 index bab6387..0000000 --- a/packages/rollup/test/workspace_link/bar.js +++ /dev/null
@@ -1 +0,0 @@ -export const bar = 'bar'; \ No newline at end of file
diff --git a/packages/rollup/test/workspace_link/foo.js b/packages/rollup/test/workspace_link/foo.js deleted file mode 100644 index f4596d5..0000000 --- a/packages/rollup/test/workspace_link/foo.js +++ /dev/null
@@ -1 +0,0 @@ -export const foo = 'foo'; \ No newline at end of file
diff --git a/packages/rollup/test/workspace_link/main.js b/packages/rollup/test/workspace_link/main.js deleted file mode 100644 index eb83372..0000000 --- a/packages/rollup/test/workspace_link/main.js +++ /dev/null
@@ -1,5 +0,0 @@ -import * as foo from 'build_bazel_rules_nodejs/packages/rollup/test/workspace_link/foo'; -import * as bar from './bar'; - -console.log(foo); -console.log(bar);
diff --git a/packages/rollup/test/workspace_link/rollup.config.js b/packages/rollup/test/workspace_link/rollup.config.js deleted file mode 100644 index da6ceea..0000000 --- a/packages/rollup/test/workspace_link/rollup.config.js +++ /dev/null
@@ -1,15 +0,0 @@ -import commonjs from '@rollup/plugin-commonjs'; -import nodeResolve from '@rollup/plugin-node-resolve'; - -module.exports = { - onwarn: (warning) => { - // Always fail on warnings, assuming we don't know which are harmless. - // We can add exclusions here based on warning.code, if we discover some - // types of warning should always be ignored under bazel. - throw new Error(warning.message); - }, - plugins: [ - nodeResolve(), - commonjs(), - ], -};
diff --git a/packages/rollup/test/workspace_link/spec.js b/packages/rollup/test/workspace_link/spec.js deleted file mode 100644 index af26734..0000000 --- a/packages/rollup/test/workspace_link/spec.js +++ /dev/null
@@ -1,11 +0,0 @@ -const fs = require('fs'); -const runfiles = require(process.env['BAZEL_NODE_RUNFILES_HELPER']); - -describe('rollup', () => { - it('should bundle absolute & relative imports', async () => { - const file = runfiles.resolvePackageRelative('bundle.js'); - const bundle = fs.readFileSync(file, 'utf-8'); - expect(bundle).toContain(`const foo = 'foo';`); - expect(bundle).toContain(`const bar = 'bar';`); - }); -});