Refactor chat completion

This commit is contained in:
maver 2023-06-03 16:48:00 +02:00
parent fe43b58cb0
commit 1adad6105a
1 changed files with 12 additions and 11 deletions

View File

@ -9,36 +9,37 @@ const ChatCompletion = {
return { return {
map: [], map: [],
add(identifier, message) { add(identifier, message) {
this.map.push({identifier: identifier, message: message}) this.map.push({ identifier, message });
return this; return this;
}, },
insertBefore(identifier, insertIdentifier, insert) { insertBefore(identifier, insertIdentifier, insert) {
const index = this.getMessageIndex(identifier); const index = this.getMessageIndex(identifier);
if (index === -1) throw new Error(`Identifier ${identifier} not found`); this.map.splice(this.assertIndex(index, identifier), 0, { identifier: insertIdentifier, message: insert });
this.map.splice(index, 0, {identifier: insertIdentifier, message: insert});
return this; return this;
}, },
insertAfter(identifier, insertIdentifier, insert) { insertAfter(identifier, insertIdentifier, insert) {
const index = this.getMessageIndex(identifier); const index = this.getMessageIndex(identifier);
if (index === -1) throw new Error(`Identifier ${identifier} not found`); this.map.splice(this.assertIndex(index, identifier) + 1, 0, { identifier: insertIdentifier, message: insert });
this.map.splice(index + 1, 0, {identifier: insertIdentifier, message: insert});
return this; return this;
}, },
replace(identifier, replacement) { replace(identifier, replacement) {
const index = this.getMessageIndex(identifier); const index = this.getMessageIndex(identifier);
if (index === -1) throw new Error(`Identifier ${identifier} not found`); this.map[this.assertIndex(index, identifier)] = { identifier, message: replacement };
this.map[index] = {identifier: identifier, message: replacement};
return this; return this;
}, },
remove(identifier) { remove(identifier) {
const index = this.getMessageIndex(identifier); const index = this.getMessageIndex(identifier);
if (index === -1) throw new Error(`Identifier ${identifier} not found`); this.map.splice(this.assertIndex(index, identifier), 1);
this.map.splice(index, 1);
return this; return this;
}, },
assertIndex(index, identifier) {
if (index === -1) {
throw new IdentifierNotFoundError(`Identifier ${identifier} not found`);
}
return index;
},
getMessageIndex(identifier) { getMessageIndex(identifier) {
const index = this.map.findIndex(message => message.identifier === identifier) return this.map.findIndex(message => message.identifier === identifier);
return -1 === index ? false : index;
}, },
makeSystemMessage(content) { makeSystemMessage(content) {
return this.makeMessage('system', content); return this.makeMessage('system', content);