iamkun / iamkun/dayjs

dayjs(string, formats) mutates passed array of formats

Open
#2,136 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
48.7k
Forks
2.5k
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**
Runnable code: https://runkit.com/victor-homyakov/day-js-second-param-mutation

```js
const dayjs = require('dayjs');
const FORMATS = ['DD-MM-YYYY', 'DD.MM.YYYY'];
console.log('1', FORMATS, Object.keys(FORMATS));
const d1 = dayjs('22.11.2022', FORMATS);
console.log('2', FORMATS, Object.keys(FORMATS));
```

Console output:
```
1 ["DD-MM-YYYY", "DD.MM.YYYY"] ["0", "1"]
2 ["DD-MM-YYYY", "DD.MM.YYYY"] ["0", "1", "date", "args"]
```

**Expected behavior**
Expected console output:
```
1 ["DD-MM-YYYY", "DD.MM.YYYY"] ["0", "1"]
2 ["DD-MM-YYYY", "DD.MM.YYYY"] ["0", "1"]
```

**Information**
- Day.js Version: from 1.9.0 to 1.11.6, maybe older versions
- OS: MacOS
- Time zone: GMT+04:00

**Details**

The problem is in the code at https://github.com/iamkun/dayjs/blob/v1.11.6/src/index.js#L41

```js
const dayjs = function (date, c) {
// skipped...
const cfg = typeof c === 'object' ? c : {}
cfg.date = date
cfg.args = arguments
```

The type of any array is 'object': `typeof [] === 'object'`. When called as `daysjs(string, array)`, it uses the passed array as a configuration object `cfg`, and writes to it two fields `date`, `args`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.