Is there any utility to apply delta object of Y.Array Event to javascript array. For example I get this delta object in Y.Array observer:
[
{
"retain": 1
},
{
"insert": [
{
"copytext": "Hello world",
"id": "1104",
}
]
},
{
"retain": 1
},
{
"delete": 1
}
]
So we have an array where we leave one element, then insert new, then leave one and then delete one. This is a sequence of actions that should be applied to a regular JavaScript array. What is the best way to do that?
raine
November 6, 2023, 2:15pm
2
Hi, welcome.
Iām not aware of a built-in utility to apply delta objects to normal Javascript arrays, but you can define it yourself like this:
const applyDelta = (input, delta) => {
let cursor = 0
let output = []
delta.forEach(op => {
if (op.delete) {
cursor += op.delete
}
else if (op.retain) {
output.push(...input.slice(cursor, cursor + op.retain))
cursor += op.retain
}
else if (op.insert) {
output.push(...op.insert)
}
})
output.push(...input.slice(cursor))
return output
}
console.log(applyDelta(['a', 'b', 'c'], [
{
"retain": 1
},
{
"insert": [
{
"copytext": "Hello world",
"id": "1104",
}
]
},
{
"retain": 1
},
{
"delete": 1
}
]))
Result:
['a', { copytext: 'Hello world', id: '1104' }, 'b' ]
1 Like