Commit 4e47f98d authored by Phil Booth's avatar Phil Booth

fix(code): ensure sane grow behaviour for overflowed items

parent bb08e45a
......@@ -113,6 +113,18 @@ adds items to the array.
It takes one argument,
which is the number
of items to grow the array by.
The new length of the array
will be the old length
plus the number you pass to `grow`.
If the current state of the array
includes overflowed indices,
`grow` will take care
to move those items
in to the freshly-created
available space,
so that the correct order is maintained
for your data.
The caller is responsible
for ensuring they don't overwrite
......
......@@ -24,7 +24,11 @@ class Hoopy extends Array {
if (isIndexOverflowed) {
for (i = 0; i <= index; ++i) {
this[size + i] = this[i]
let j = size + i
if (j >= newSize) {
j %= newSize
}
this[j] = this[i]
this[i] = undefined
}
}
......
......@@ -255,3 +255,53 @@ suite('instantiate, size=2:', () => {
})
})
suite('instantiate and overflow, size=3:', () => {
let hoopy
setup(() => {
hoopy = new Hoopy(3)
hoopy[2] = 'foo'
hoopy[3] = 'bar'
hoopy[4] = 'baz'
})
test('data is correct', () => {
assert.equal(hoopy.length, 3)
assert.equal(hoopy[2], 'foo')
assert.equal(hoopy[3], 'bar')
assert.equal(hoopy[4], 'baz')
assert.equal(hoopy[0], hoopy[3])
assert.equal(hoopy[1], hoopy[4])
})
suite('grow, by=1:', () => {
setup(() => {
hoopy.grow(1)
})
test('data is correct', () => {
assert.equal(hoopy.length, 4)
assert.equal(hoopy[2], 'foo')
assert.equal(hoopy[3], 'bar')
assert.equal(hoopy[4], 'baz')
assert.equal(hoopy[0], hoopy[4])
assert.isUndefined(hoopy[1])
})
})
suite('grow, by=2:', () => {
setup(() => {
hoopy.grow(2)
})
test('data is correct', () => {
assert.equal(hoopy.length, 5)
assert.equal(hoopy[2], 'foo')
assert.equal(hoopy[3], 'bar')
assert.equal(hoopy[4], 'baz')
assert.isUndefined(hoopy[0])
assert.isUndefined(hoopy[1])
})
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment