Skip to content

Instantly share code, notes, and snippets.

@ryanguill
Last active April 9, 2020 13:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanguill/e7b183b0f33eb2c60ed2c2bd26be6149 to your computer and use it in GitHub Desktop.
Save ryanguill/e7b183b0f33eb2c60ed2c2bd26be6149 to your computer and use it in GitHub Desktop.
<cfscript>
/*
this is what im actually working on, but isnt really the point of this discussion,
but for clarity, I have a process where I am needing to (conditionally) map
from one uuid to another, so I am making a litle closure to keep track. If
I ask for an ID that hasnt been seen yet then it just creates a new uuid for me and
then keeps track of it going forward.
*/
function makeIdMapper () {
var o = {
aliases = {},
get: function (input) {
if (!structKeyExists(o.aliases, input)) {
o.set(input, createUUID());
}
return o.aliases[input];
},
set: function (input, output) {
o.aliases[input] = output;
return o;
}
};
return o;
}
idMapper = makeIdMapper();
/* show that it works */
writedump(var=idMapper.get("foo"), label="idMapper.get('foo')");
writedump(var=idMapper.get("bar"), label="idMapper.get('bar')");
writedump(var=idMapper.get("foo") != idMapper.get("bar"), label="foo != bar");
writedump(var=idMapper.get("foo") == idMapper.get("foo"), label="foo == foo");
writedump(var=idMapper, label="idMapper");
/*
this is what im really interested in discussing - the concept, this particular api, any improvements, etc
I cant dump `variables` on trycf, so using request as an example, but any structure should do.
would like to make this work cf10+, lucee 4.5+
*/
function destructure (inputStruct, targetScopeOrStruct = {}, mapping = {}) {
for (var key in inputStruct) {
var outputKey = key;
if (structKeyExists(mapping, key)) {
outputKey = mapping[key];
}
if (len(outputKey)) {
targetScopeOrStruct[outputKey] = inputStruct[key];
}
}
return targetScopeOrStruct;
}
writedump(var=request, label="request scope");
destructure(makeIdMapper(), request, {"get": "getMappedID", "set": "", "aliases": ""});
writedump(var=request, label="request scope");
writedump(var=request.getMappedID("foo"), label="request.getMappedID('foo')");
writedump(var=request.getMappedID("bar"), label="request.getMappedID('bar')");
writedump(var=request.getMappedID("foo") != request.getMappedID("bar"), label="foo != bar");
writedump(var=request.getMappedID("foo") == request.getMappedID("foo"), label="foo == foo");
/*
some more examples
*/
struct1 = {
"foo": "foo",
"bar": "bar"
};
struct2 = destructure(struct1, {});
writedump(var=struct2, label="should have foo and bar");
destructure(struct1, struct2, {"foo": "baz", "bar": "bat"});
writedump(var=struct2, label="should have foo, bar, baz and bat");
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment