Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Default array should be created only if the key is a number and the index is in order #42

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions lib/util/defaultObject.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import isEmpty from './isEmpty';

function isInt(value) {
function isIntAndInRange(value, maxIndex) {
if (isNaN(value)) {
return false;
}
const x = parseFloat(value);
return (x | 0) === x;
return (x | 0) === x && (x >= 0 && x <= maxIndex);
}

function isArrayUpdate(updates) {
for (const updateKey of Object.keys(updates)) {
if (!isInt(updateKey)) { return false; }
const keys = Object.keys(updates);
const maxIndex = keys.length - 1;
for (const updateKey of keys) {
if (!isIntAndInRange(updateKey, maxIndex)) { return false; }
}

return true;
Expand Down
12 changes: 12 additions & 0 deletions test/updeep-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,18 @@ describe('updeep', () => {
expect(result).to.eql({ 0: 'hi', '1a': 'world' });
});

it('can create array if all keys are numbers and the index is in order from zero', () => {
const result = u({ 0: 'hi', '1': 'world', 2: 'ind2' }, null);

expect(result).to.eql(['hi', 'world', 'ind2']);
});

it('doest not create array if all keys are numbers but the index is not in order from zero', () => {
const result = u({ 0: 'hi', '2': 'world', 3: 'ind3' }, null);

expect(result).to.eql({ 0: 'hi', '2': 'world', 3: 'ind3' });
});

it('can add an element to an array', () => {
const object = [];
const result = u({ 0: 3 }, object);
Expand Down