Skip to content

Instantly share code, notes, and snippets.

@LeZuse
Created July 14, 2012 16:15
Show Gist options
  • Select an option

  • Save LeZuse/3111956 to your computer and use it in GitHub Desktop.

Select an option

Save LeZuse/3111956 to your computer and use it in GitHub Desktop.
OT: compose
<html>
<head>
<title>testing</title>
</head>
<body>
<script type="text/javascript" src="compose.js"></script>
<div id="res"></div>
</body>
</html>
var compose = function (str, op1, op2) {
var composed = [];
var nextOp1Action = op1.shift(), nextOp2Action = op2.shift();
var max = 500;
Object.prototype.len = function() {
return this.retain || this.insert && this.insert.length || this['delete'];
};
Object.prototype.splitAction = function(splitBy)
{
var maxLen = splitBy.len();
if (maxLen < this.len()) {
if (this.retain) {
return [{'retain': maxLen}, {'retain': this.retain - maxLen}];
}
if (this['delete']) {
return [{'delete': maxLen}, {'delete': this['delete'] - maxLen}];
}
if (this.insert) {
return [{'insert': this.insert.substring(0, maxLen)}, {'insert': this.insert.substring(maxLen)}];
}
}
return [this, null]; // we dont need to split
};
while ((nextOp1Action || op1.length) && (nextOp2Action || op2.length)) {
// console.log('op1a', nextOp1Action, 'op2a', nextOp2Action);
// get the second action to compare with if we dont have one
if (!nextOp1Action) nextOp1Action = op1.shift();
if (!nextOp2Action) nextOp2Action = op2.shift();
if (nextOp1Action && nextOp1Action['delete']) {
composed.push(nextOp1Action);
nextOp1Action = op1.shift();
}
if (nextOp2Action && nextOp2Action.insert) {
composed.push(nextOp2Action);
nextOp2Action = op2.shift();
}
// split to common length
if (nextOp1Action && nextOp2Action) {
var pairOne = nextOp1Action.splitAction(nextOp2Action);
var pairTwo = nextOp2Action.splitAction(nextOp1Action);
// console.log('pairs', pairOne, pairTwo);
// insert/delete takes precedence over retain
if (pairOne[0].retain) {
composed.push(pairTwo[0]);
}
else if (pairTwo[0].retain) {
composed.push(pairOne[0]);
}
nextOp1Action = pairOne[1];
nextOp2Action = pairTwo[1];
}
if (!-- max) break; // safe lock
}
if (nextOp1Action) {
composed.push(nextOp1Action);
}
if (op1.length) {
composed = composed.concat(op1);
}
if (nextOp2Action) {
composed.push(nextOp2Action);
}
if (op2.length) {
composed = composed.concat(op2);
}
return composed;
};
if (typeof module !== 'undefined') {
module.exports = compose;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment