Skip to content

Instantly share code, notes, and snippets.

@csuwildcat
Last active October 9, 2024 14:26
Show Gist options
  • Save csuwildcat/5d0cac8192681e503d0b2331d3f5feac to your computer and use it in GitHub Desktop.
Save csuwildcat/5d0cac8192681e503d0b2331d3f5feac to your computer and use it in GitHub Desktop.
protocols = (() => {
const definitions = {};
const functions = {
alias: (path, map) => {
// Handling alias definitions, store the protocol URI with each alias
for (const alias in map) {
definitions[alias] = map[alias];
console.log(`Alias '${alias}' added with protocol URI: ${map[alias].protocol}`);
}
},
definition: (path) => {
return definitions[path[0]];
},
set: (path, value, templateNode) => {
console.log(`Set value at path: ${path.join('.')}, value:`, value, `, template:`, templateNode);
},
get: (path, templateNode) => {
console.log(`Get value at path: ${path.join('.')}, template:`, templateNode);
},
add: (path, value, templateNode) => {
console.log(`Add value at path: ${path.join('.')}, value:`, value, `, template:`, templateNode);
},
modify: (path, value, templateNode) => {
console.log(`Modify value at path: ${path.join('.')}, value:`, value, `, template:`, templateNode);
},
delete: (path, templateNode) => {
console.log(`Delete value at path: ${path.join('.')}, template:`, templateNode);
},
query: (path, templateNode) => {
console.log(`Query at path: ${path.join('.')}, template:`, templateNode);
},
};
function createDynamicProxy(structure, protocol, functions, path = []) {
return new Proxy(() => structure, {
apply(target, thisArg, [command, arg]) {
if (typeof functions[command] === 'function') {
return functions[command](path, arg, target(), protocol);
}
throw new Error(`Unknown command: ${command}`);
},
get(target, prop) {
const currentPath = [...path, prop];
if (path.length === 0 && definitions[prop]) {
const { structure, protocol } = definitions[prop];
return createDynamicProxy(structure, protocol, functions, [prop]);
}
// Handle nested objects by returning another proxy for chaining
const structureValue = target()[prop];
if (typeof structureValue === 'object' && structureValue !== null) {
return createDynamicProxy(structureValue, protocol, functions, currentPath);
}
return (command, value) => {
if (typeof functions[command] === 'function') {
return functions[command](currentPath, value, target(), protocol);
}
throw new Error(`Unknown command: ${command}`);
};
},
});
}
return createDynamicProxy({}, '', functions);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment