diff --git a/spec/stdlib/underscore-extensions-spec.coffee b/spec/stdlib/underscore-extensions-spec.coffee index 5ae310cde..d3910dd08 100644 --- a/spec/stdlib/underscore-extensions-spec.coffee +++ b/spec/stdlib/underscore-extensions-spec.coffee @@ -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'] diff --git a/src/stdlib/underscore-extensions.coffee b/src/stdlib/underscore-extensions.coffee index 33dde9f48..defdb576f 100644 --- a/src/stdlib/underscore-extensions.coffee +++ b/src/stdlib/underscore-extensions.coffee @@ -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