Replies: 3 comments
-
Hi, $pickPaths = fn ($paths, $ob) => reduce(fn ($res, $path) => setPath($path, path($path, $ob), $res), [], $paths); I don't think you should worry about |
Beta Was this translation helpful? Give feedback.
-
Hi again, The main benefit of a pickPaths function as I was proposing is that the path is analyzed and processed (dot notation or not, array of keys or single key etc) only once, not twice as is the case in the one liner above (path and setPath both have to do it separately). But of course, I had to write close to 30 lines of code in PHP, so there's that... |
Beta Was this translation helpful? Give feedback.
-
I guess you are right. |
Beta Was this translation helpful? Give feedback.
-
Hey…
Here’s an idea if you’re interested. I hope I didn't miss the exact function I'm suggesting in the library!
I have a configuration object for the application that is stored in a Yaml file. Instead of loading the application and having it make an HTTP request to get some initialization data, I like to incorporate that data in index.php in the form of a JS script that is inserted at load time.
So after reading the Yaml file, I get a JSON object, but I don’t want to include the whole object in index.php, just the data needed by the client.
If I have the following object (tiny for illustration purposes):
$object = {
param1 => val1,
param2 => {
param2a => val2a
param2b => val2b,
},
param3 => val3
}
and I just want to transfer values val2a and val3 while maintaining the same structure. I’d like to be able to do :
$paths = [
‘param2.param2a’,
‘param3’
];
$extracted = Idles\pickPaths($paths, $object);
this would return :
{
param2 => {
param2a => val2a,
},
param3 => val3
}
If I wanted to obtain the same object but with the paths removed :
$extracted = Idles\omitPaths($paths, $object);
and this would return :
{
param1 => val1,
param2 => {
param 2b => val2b
}
}
I like the fact that the list of paths is concisely expressed as a list of strings. If the paths are later processed in a loop however, we’re creating a new array with each iteration if we use library functions (to access and set individual paths) as they are immutable. It would seem more efficient to have a function that is able to process a list of paths in a single step, as proposed here.
Anyway, that’s it!
Beta Was this translation helpful? Give feedback.
All reactions