hench/module/helpers/mutation-helper.mjs

96 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2024-12-04 14:51:41 -05:00
function getValueAtPath(obj, fieldPath) {
2024-12-02 22:18:47 -05:00
const pathSequence = fieldPath.split('.');
let pointer = obj;
for(let i = 0; i < pathSequence.length; i++) {
pointer = pointer[pathSequence[i]];
}
return pointer;
}
2024-12-04 14:51:41 -05:00
function copyAndMutateAtPath(obj, fieldPath, val) {
2024-12-02 22:18:47 -05:00
const copy = deepCopy(obj);
const changed = mutateAtPath(copy, fieldPath, val);
return changed;
}
function mutateAtPath(obj, fieldPath, val) {
2024-12-03 22:17:31 -05:00
if(fieldPath === "") {
return val;
}
2024-12-02 22:18:47 -05:00
const pathSequence = fieldPath.split('.');
let pointer = obj;
for(let i = 0; i < pathSequence.length - 1; i++) {
pointer = pointer[pathSequence[i]];
}
pointer[pathSequence[pathSequence.length - 1]] = val;
return obj;
}
2024-12-04 14:51:41 -05:00
function deepCopy(obj) {
2024-12-02 22:18:47 -05:00
return structuredClone(obj);
2024-12-03 22:17:31 -05:00
}
2024-12-04 14:51:41 -05:00
function getDataPathFromString(dataPathString) {
2024-12-03 22:17:31 -05:00
const arraySplit = dataPathString.indexOf('[');
const isArray = arraySplit > 0;
if(isArray) {
const preTokens = dataPathString.split('[');
const postTokens = preTokens[1].split(']');
const prefix = preTokens[0];
const postfixRaw = postTokens[1];
const postfix = postfixRaw.indexOf('.') === 0 ? postfixRaw.slice(1) : postfixRaw;
const index = parseInt(postTokens[0]);
return {
path: prefix,
isArray: true,
index: index,
subPath: postfix,
};
} else {
return {
path: dataPathString,
isArray: false,
index: 0,
subPath: null,
};
}
}
2024-12-11 16:17:00 -05:00
export async function updateField(actor, dataPathString, value) {
2024-12-03 22:17:31 -05:00
const dataPath = getDataPathFromString(dataPathString);
console.log(`Converted ${dataPathString} to:`);
console.log(dataPath);
2024-12-04 16:20:08 -05:00
console.log(`Writing: ${value} (${typeof value})`);
2024-12-03 22:17:31 -05:00
if(dataPath.isArray) {
const initial = getValueAtPath(actor, dataPath.path);
const copy = initial.map(e => deepCopy(e));
copy[dataPath.index] = copyAndMutateAtPath(initial[dataPath.index], dataPath.subPath, value);
2024-12-04 16:20:08 -05:00
console.log(`Array write at index ${dataPath.index}`);
console.log(copy);
2024-12-11 16:17:00 -05:00
await actor.update({
2024-12-03 22:17:31 -05:00
[dataPath.path]: copy,
});
} else {
2024-12-11 16:17:00 -05:00
await actor.update({
2024-12-03 22:17:31 -05:00
[dataPath.path]: value
});
}
2024-12-02 22:18:47 -05:00
}