Add _.spliceWithArray to avoid stack overflows when splicing huge arrays

This commit is contained in:
Corey Johnson & Nathan Sobo 2013-04-23 11:16:55 -07:00
parent 1ccf026a83
commit 9f235103f8
2 changed files with 19 additions and 0 deletions

View File

@ -53,4 +53,15 @@ describe "underscore extensions", ->
expect(_.underscore("CoreyDaleJohnson")).toBe "corey_dale_johnson"
expect(_.underscore("corey_dale_johnson")).toBe "corey_dale_johnson"
describe "spliceWithArray(originalArray, start, length, insertedArray, chunkSize)", ->
describe "when the inserted array is smaller than the chunk size", ->
it "splices the array in place", ->
array = ['a', 'b', 'c']
_.spliceWithArray(array, 1, 1, ['v', 'w', 'x', 'y', 'z'], 100)
expect(array).toEqual ['a', 'v', 'w', 'x', 'y', 'z', 'c']
describe "when the inserted array is larger than the chunk size", ->
it "splices the array in place one chunk at a time (to avoid stack overflows)", ->
array = ['a', 'b', 'c']
_.spliceWithArray(array, 1, 1, ['v', 'w', 'x', 'y', 'z'], 2)
expect(array).toEqual ['a', 'v', 'w', 'x', 'y', 'z', 'c']

View File

@ -5,6 +5,14 @@ _.mixin
index = array.indexOf(element)
array.splice(index, 1) if index >= 0
spliceWithArray: (originalArray, start, length, insertedArray, chunkSize=100000) ->
if insertedArray.length < chunkSize
originalArray.splice(start, length, insertedArray...)
else
originalArray.splice(start, length)
for chunkStart in [0..insertedArray.length] by chunkSize
originalArray.splice(start + chunkStart, 0, insertedArray.slice(chunkStart, chunkStart + chunkSize)...)
sum: (array) ->
sum = 0
sum += elt for elt in array