mirror of
https://github.com/pulsar-edit/pulsar.git
synced 2024-09-21 07:58:04 +03:00
Add _.spliceWithArray to avoid stack overflows when splicing huge arrays
This commit is contained in:
parent
1ccf026a83
commit
9f235103f8
@ -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']
|
||||
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user