Implemented spliceEsonArray

This commit is contained in:
jos 2017-12-15 12:59:45 +01:00
parent f491a00575
commit a059eb844e
3 changed files with 42 additions and 4 deletions

View File

@ -23,6 +23,7 @@
"flow": "flow; test $? -eq 0 -o $? -eq 2",
"test": "ava --verbose",
"test-eson": "ava --verbose test/eson.test.js",
"test-patch": "ava --verbose test/patchEson.test.js",
"watch:test": "ava --verbose --watch"
},
"dependencies": {

View File

@ -71,6 +71,33 @@ export function mapEsonArray (esonArray, callback) {
return result
}
/**
* Splice an eson Array: delete items and insert items
* @param {ESON} esonArray
* @param {number} start
* @param {number} deleteCount
* @param {Array} [insertItems]
*/
export function spliceEsonArray(esonArray, start, deleteCount, insertItems = []) {
let splicedArray = {}
const originalLength = esonArray._meta.length
for (let i = 0; i < start; i++) {
splicedArray[i] = esonArray[i]
}
for (let i = 0; i < insertItems.length; i++) {
splicedArray[i + start] = insertItems[i]
}
for (let i = start + deleteCount; i < originalLength; i++) {
splicedArray[i - deleteCount] = esonArray[i]
}
const length = originalLength - deleteCount + insertItems.length
splicedArray._meta = setIn(esonArray._meta, ['length'], length)
return splicedArray
}
/**
* Expand function which will expand all nodes
* @param {Path} path

View File

@ -3,11 +3,12 @@ import test from 'ava'
import { setIn, getIn, deleteIn } from '../src/utils/immutabilityHelpers'
import {
esonToJson, toEsonPath, toJsonPath, pathExists, transform, traverse,
parseJSONPointer, compileJSONPointer,
parseJSONPointer, compileJSONPointer,
jsonToEson,
expand, expandOne, expandPath, applyErrors, search, nextSearchResult, previousSearchResult,
applySelection, pathsFromSelection,
SELECTED, SELECTED_END
expand, expandOne, expandPath, applyErrors, search, nextSearchResult,
previousSearchResult,
applySelection, pathsFromSelection,
SELECTED, SELECTED_END, spliceEsonArray
} from '../src/eson'
import deepMap from "deep-map/lib/index"
@ -530,6 +531,15 @@ test('pathsFromSelection (after)', t => {
t.deepEqual(pathsFromSelection(ESON1, selection), [])
})
test('spliceEsonArray', t => {
const eson = jsonToEson([1,2,3])
t.deepEqual(replaceIds(spliceEsonArray(eson, 1, 1)), replaceIds(jsonToEson([1,3])))
t.deepEqual(replaceIds(spliceEsonArray(eson, 1, 5)), replaceIds(jsonToEson([1])))
t.deepEqual(replaceIds(spliceEsonArray(eson, 1, 0, [10])), replaceIds(jsonToEson([1,5,3])))
t.deepEqual(replaceIds(spliceEsonArray(eson, 1, 0, [10,20])), replaceIds(jsonToEson([1,10,20,3])))
})
// helper function to replace all id properties with a constant value
function replaceIds (eson, value = '[ID]') {
eson._meta.id = value