import {test as nodeTest} from 'node:test'; import {runInNewContext} from 'node:vm'; import {Linter} from 'eslint'; import outdent from 'outdent'; import {getTester, parsers} from './utils/test.js'; const {test, rule} = getTester(import.meta); test({ valid: [], invalid: [ ...[ ['new Array("hello" /* keep */ + "world");', '["hello" /* keep */ + "world"];'], ['new Array([/* keep */ "value"]);', '[[/* keep */ "value"]];'], ['new Array({/* keep */ value: 1});', '[{/* keep */ value: 1}];'], ['new Array(["hello", // keep\r\n "world"]);', '[["hello", // keep\r\n "world"]];'], ['use()\nnew Array([/* keep */ "value"]);', 'use()\n;[[/* keep */ "value"]];'], ].map(([code, output]) => ({code, output, errors: [{messageId: 'error'}]})), { code: 'new Array(...getValues(/* keep */));', errors: [{messageId: 'error', suggestions: [{messageId: 'spread', output: '[...getValues(/* keep */)];'}]}], }, ], }); test({ valid: [], invalid: [ { code: 'new Array("value" as /* keep */ string);', output: '["value" as /* keep */ string];', languageOptions: {parser: parsers.typescript}, errors: [{messageId: 'error'}], }, ...[ 'new Array((/* keep */ "value"));', 'new Array(("value" /* keep */));', 'new Array(...values /* keep */);', 'new Array(1 /* keep */ + 2);', ].map(code => ({code, errors: [{messageId: 'error', suggestions: []}]})), ], }); nodeTest('commented nonnumeric arguments remain a single array element', t => { const linter = new Linter(); const code = 'const result = new Array({/* keep */ value: "hello"}); JSON.stringify({length: result.length, value: result[0]});'; const {output, fixed, messages} = linter.verifyAndFix(code, { plugins: {unicorn: {rules: {'no-new-array': rule}}}, rules: {'unicorn/no-new-array': 'error'}, }); t.assert.strictEqual(fixed, true); t.assert.deepStrictEqual(messages, []); t.assert.ok(output.includes('/* keep */')); const expected = '{"length":1,"value":{"value":"hello"}}'; t.assert.strictEqual(runInNewContext(code), expected); t.assert.strictEqual(runInNewContext(output), expected); }); nodeTest('commented spread arguments remain suggestions and evaluate once', t => { const linter = new Linter(); const code = 'new Array(...getValues(/* keep */));'; const config = { plugins: {unicorn: {rules: {'no-new-array': rule}}}, rules: {'unicorn/no-new-array': 'error'}, }; const {output, fixed, messages} = linter.verifyAndFix(code, config); t.assert.strictEqual(fixed, false); t.assert.strictEqual(output, code); t.assert.strictEqual(messages.length, 1); t.assert.strictEqual(messages[0].suggestions?.length, 1); const {fix} = messages[0].suggestions[0]; const suggested = code.slice(0, fix.range[0]) + fix.text + code.slice(fix.range[1]); t.assert.ok(suggested.includes('/* keep */')); for (const source of [code, suggested]) { let evaluations = 0; const result = runInNewContext(source, { getValues() { evaluations++; return ['hello', 'world']; }, }); t.assert.strictEqual(evaluations, 1); t.assert.strictEqual(JSON.stringify(result), '["hello","world"]'); } }); test.snapshot({ valid: [ 'const array = Array.from({length: 1})', // ESLint builtin rule `no-array-constructor` cases 'const array = new Array()', 'const array = new Array', 'const array = new Array(1, 2)', 'const array = Array(1, 2)', // `unicorn/new-for-builtins` cases 'const array = Array(1)', ], invalid: [ outdent` const modes = new Set(['foo']); modes.clear(); new Array(modes.size ? 1 : 'x'); `, 'const modes = new Set(["foo"]); modes.clear(); new Array((modes.size && 1) || value);', 'const object = {value: true}; Object.defineProperty(object, "value", {get() { return false; }}); new Array(object.value ? 1 : value);', { code: 'const modes = new Set(["foo"]); modes.clear(); new Array((modes.size ? "x" : 1) as number);', languageOptions: {parser: parsers.typescript}, }, 'const array = new Array(1)', // This is actually `[]`, but a length is not fixed outdent` const zero = 0; const array = new Array(zero); `, // A variable named `length` outdent` const length = 1; const array = new Array(length); `, 'const array = new Array(1.5)', 'const array = new Array(Number("1"))', 'const array = new Array("1")', 'const array = new Array(null)', 'const array = new Array(("1"))', 'const array = new Array((0, 1))', outdent` const foo = [] new Array("bar").forEach(baz) `, // Number 'new Array(0xff)', 'new Array(Math.PI | foo)', 'new Array(Math.min(foo, bar))', 'new Array(Number(foo))', 'new Array(Number.MAX_SAFE_INTEGER)', 'new Array(parseInt(foo))', 'new Array(Number.parseInt(foo))', 'new Array(+foo)', 'new Array(-Math.PI)', 'new Array(-"-2")', 'new Array(foo.length)', 'const array = [1]; new Array(array.length)', 'const text = "foo"; new Array(text.length)', 'const foo = 1; new Array(foo + 2)', 'new Array(foo - 2)', 'new Array(foo -= 2)', 'new Array(foo ? 1 : 2)', 'const truthy = "truthy"; new Array(truthy ? 1 : foo)', 'const falsy = !"truthy"; new Array(falsy ? foo : 1)', 'new Array((1n, 2))', 'new Array(Number.NaN)', 'new Array(NaN)', 'new Array(foo >>> bar)', 'new Array(foo >>>= bar)', 'new Array(++bar.length)', 'new Array(bar.length++)', 'new Array(foo = bar.length)', // Not number 'new Array("0xff")', 'new Array(Math.NON_EXISTS_PROPERTY)', 'new Array(Math.NON_EXISTS_METHOD(foo))', 'new Array(Math[min](foo, bar))', 'new Array(Number[MAX_SAFE_INTEGER])', 'new Array(new Number(foo))', 'const foo = 1; new Array(foo + "2")', 'new Array(foo - 2n)', 'new Array(foo -= 2n)', 'new Array(foo instanceof 1)', 'new Array(foo || 1)', 'new Array(foo ||= 1)', 'new Array(foo ? 1n : 2)', 'new Array((1, 2n))', 'new Array(-foo)', 'new Array(~foo)', 'new Array(typeof 1)', 'const truthy = "truthy"; new Array(truthy ? foo : 1)', 'const falsy = !"truthy"; new Array(falsy ? 1 : foo)', 'new Array(unknown ? foo : 1)', 'new Array(unknown ? 1 : foo)', 'new Array(++foo)', 'const array = new Array(foo)', 'const array = new Array(length)', outdent` const foo = [] new Array(bar).forEach(baz) `, ...[ '...[foo]', '...foo', '...[...foo]', // The following cases we can know the result, but we are not auto-fixing them '...[1]', '...["1"]', '...[1, "1"]', ].map(argumentText => `const array = new Array(${argumentText})`), outdent` const foo = [] new Array(...bar).forEach(baz) `, ], }); test({ valid: [], invalid: [ { code: 'const object = {}; Object.defineProperty(object, "length", {get() { return "foo"; }}); new Array(object.length);', errors: [{messageId: 'error'}], }, { code: 'const array = []; new Array(1 + array.length);', errors: [{messageId: 'error'}], }, { code: 'const alias = condition; var condition = true; new Array(alias ? "x" : 1);', errors: [{messageId: 'error'}], }, // A number is a length, and there is no dense spelling of a holey array, so it is reported without a fix or suggestion. This includes a length that makes `new Array()` throw. ...[ 'new Array(1.5)', 'new Array(-1)', 'new Array(1 / 2)', 'const size = 3; new Array(size / 2);', 'const size = 3; new Array(size * 2);', 'new Array(-0)', 'new Array(2.5 * 2)', 'new Array(Infinity)', ].map(code => ({ code, errors: [{messageId: 'error'}], })), ...[ 'new Array(0xff)', 'new Array(1e2)', 'new Array(0b1)', 'new Array(1_0)', ].map(code => ({ code: `const array = ${code};`, errors: 1, })), // A comment inside the call is not dropped by the fix or the suggestion ...[ 'new Array(/* the size */ 3);', 'new /* c */ Array(1);', 'new Array(1 /* c */);', 'new Array(/* c */ "x");', 'new /* c */ Array("x");', 'new Array(/* c */ ...foo);', ].map(code => ({ code, errors: [{messageId: 'error', suggestions: []}], })), ], });