<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joseph Sikorski on Medium]]></title>
        <description><![CDATA[Stories by Joseph Sikorski on Medium]]></description>
        <link>https://medium.com/@joedski?source=rss-b1946e4457d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*wWU1YcIBeZaWjEl1.</url>
            <title>Stories by Joseph Sikorski on Medium</title>
            <link>https://medium.com/@joedski?source=rss-b1946e4457d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:28:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joedski/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simple Composition of Steps that can Undo Their Work]]></title>
            <link>https://medium.com/@joedski/simple-composition-of-steps-that-can-undo-their-work-3d8046c6f159?source=rss-b1946e4457d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d8046c6f159</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[async-functions]]></category>
            <dc:creator><![CDATA[Joseph Sikorski]]></dc:creator>
            <pubDate>Wed, 11 Oct 2017 00:13:45 GMT</pubDate>
            <atom:updated>2017-10-11T00:13:45.999Z</atom:updated>
            <content:encoded><![CDATA[<p>When trying to write a (somewhat) robust system built out of multiple services that exist on different servers, it can be hard to handle cases where one step fails in a clean and consistent manner. Here, I’ll show one of the simpler ones I came up with using async/await functions in Javascript.</p><p>At its heart, I wanted to have both the forward process and the backward process colocated in the same step, and I wanted to automatically execute the backward process if the next step failed. This can be done quite easily by passing the next function as an argument to the previous, thus allowing the previous to call the next one when it’s ready to.</p><p>The way it works is:</p><ul><li>First, a Step receives a Process Context and tries to do its own thing.</li><li>If it fails, it simply lets the error throw, rejecting its returned promise.</li><li>If it succeeds, it attaches its result (if any) to the Process Context, then calls the next Step with it, awaiting on that next Step.</li><li>If the next Step fails, it catches that error and tries to <em>undo</em> its own thing.</li><li>If that undo succeeds, it just re-throws the original error(s). If that undo <em>fails</em>, it combines the resulting undo error with the original error(s) and throws those.</li></ul><p>The implementation is simple enough:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93957c1fc1e89fbfcc1d9504b4880f6/href">https://medium.com/media/f93957c1fc1e89fbfcc1d9504b4880f6/href</a></iframe><p>Looks a bit like Koa 2 middleware… A bit.</p><p>To string a bunch of these steps together seems kind of annoying at first, since you’d have to call them like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8ff848a7f1a885f3ae18d24778c4d9c/href">https://medium.com/media/d8ff848a7f1a885f3ae18d24778c4d9c/href</a></iframe><p>Not much better than callbacks.</p><p>However! Because we have functions expecting next-step functions to get passed to them, we can use compose to de-pyramidize things! Note that while compose usually seems to make things backwards, here it actually puts the steps in the expected order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb3af9ea3e3e8dacd3fc00d6cf2d198d/href">https://medium.com/media/cb3af9ea3e3e8dacd3fc00d6cf2d198d/href</a></iframe><p>Of course, instead of just passing a boring old identity function as the cap-off to the steps, you could use it to handle that extraction step, getting the actual value out of the Process Context to return…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5efb865c829285cb30cf84833e5cfb4e/href">https://medium.com/media/5efb865c829285cb30cf84833e5cfb4e/href</a></iframe><p>I don’t always go that laconic, but it is nice when I can.</p><h3>Parallel Processes</h3><p>The only tricky part I’ve found with this setup is running a bunch of steps in parallel, similar to Promise.all(). The reason it’s tricky is this:</p><ul><li>If any of the Steps failed, I wanted all of the ones that succeeded to undo their work.</li><li>If more than one Step failed, I wanted to see all their errors.</li></ul><p>The first presents us with an issue because, as written, each thing is awaiting on the next step to finish, but that next step only finishes when each thing finishes!</p><p>The second is a slight issue because any errors that do get thrown have to be combined into a bigger error, and they have to allow for that happening at different times. Everything has to “settle” before the error is finally thrown. (Technically, since each thing is awaiting on the next, nothing actually settles until the final Step in a Process settles.) This is also in contrast to Promise.all, which rejects eagerly on the first error.</p><p>Fortunately, it’s not too hairy to solve, it just takes a bit of thought. Since this is already async based, we’ll refer to this process as AllSteps, reflective of how a Promise on many things is created with Promise.all(). So, let’s start defining things.</p><ul><li>AllSteps is the Promise whose Execution we’re now defining.</li><li>AllSteps itself is Settled if every Step is Settled. (A Promise is Settled if it is either Resolved or Rejected.)</li><li>AllSteps will Resolve if every Step Resolves, and it will Resolve with a Composite Resolution created from every Step Resolution.</li><li>AllSteps will Reject if any Step Rejects, and it will Reject with a Composite Rejection created from each Step Rejection that occurred and each Step Undo Rejection that occurred, if any.</li><li>AllSteps will, if it will Reject, wait for any Step which succeeded to finish its Undo process before itself Rejecting.</li></ul><p>For getting into the details of this, take note of the second point above. Since a Promise is Settled when it is either Resolved or Rejected, this means regardless of what happens in the Step, success or throwing, we can probably just use Promise.all() to handle waiting for that Settling. To do that, of course, we’ll have to catch any errors that occur.</p><p>We’ll call this Promise.all() one the AllStepsSettled Promise, to differentiate it from the overarching AllSteps Promise. Mainly, the AllStepsSettled Promise does not actually Resolve to or Reject with any values at all, it’s simply being awaited upon for completion of all the Steps’ processes Doing or Undoing. AllSteps will then handle those values or errors separately afterwards.</p><ul><li>AllStepsSettled will Resolve when every Step has Settled, whether Rejected or Resolved. This does mean Errors must be Handled to avoid issues with Uncaught Rejections.</li></ul><p>The biggest hangup remaining then is that first point in the original list, that if any Step Rejects, all Steps which succeeded must Undo their work.</p><p>Given the current implementation, this means each Step must eventually await on a promise that both that Step and every other Step have an effect on!</p><p>To unroll this circle we’ll need to turn to one of the earlier ways Promises were frequently used, Deferreds. This will allow us to use things not within a Promise’s Executor to Resolve or Reject that Promise. The cost, of course, is heightened vigilance, since externalizing control like this can lead to difficult to debug code. In particular, we need to take care that we only call one of Deferred#resolve() or Deferred#reject(), and only once.</p><p>In this particular case, we’ll need one Deferred, the AnyRejections Deferred.</p><ul><li>The AnyRejections Deferred will be Rejected by the first Step to Reject.</li><li>The AnyRejections Deferred will be Resolved if the last Step to complete its forward process Resolves.</li><li>The AnyRejections Deferred is <em>different</em> from the AllSteps Promise, and <em>also different</em> from the AllStepsSettled Promise, although those two ultimately depend on the AnyRejections Deferred.</li></ul><p>From all that, we now have a way to clearly define how to actually handle each Step inside this AllSteps thing:</p><ul><li>To each Step, pass a Next function.</li><li>Then, execute each Step on the Process Context passed to AllSteps.</li><li>If any Error occurs, handle that Error so as to not leave Unhandled Promise Rejections. (which will crash Node going forward!)</li></ul><p>That Next function will, if called,</p><ul><li>Track the Resolution of this Step, since a Step only calls Next if it successfully completes its Do operation.</li><li>Check if this Resolution was the final one and, if so, Resolve the AnyRejections Deferred.</li><li>It will then await on the AnyRejections Deferred’s Promise. If any other Step causes AnyRejections Deferred to Reject, then this is where that Rejection back-propagates to the succeeding Steps.</li></ul><p>Handling an Error happens like this:</p><ul><li>If the Step already has a Resolution, then it succeeded in its Do Process, so it’s only here after it’s either completed its Undo process or failed to do so.</li><li>If the Step does already have a Resolution and the Error was the one that triggered the Undo Process, then handling is complete.</li><li>If the Step does already have a Resolution and the Error was <em>not</em> the one that triggered the Undo Process, track that Error as an UndoRejection for the Step. (A Step may have both a Resolution and an UndoRejection if for some reason the Do Process succeeded but the Undo Process failed.)</li><li>Otherwise, the Error was caused by the Step itself. Track the Rejection for this step and, if no other Step has Rejected yet, Reject the AnyRejection Deferred. Handling is now complete.</li></ul><p>So that’s all of Step Resolutions, Step Rejections, and Step Undo Rejections that need to be tracked. Fortunately, after all that’s done, the AllStepsSettled Promise will have Resolved so we can move forward to the final part, Resolving or Rejecting the AllSteps Promise. We already defined what happens there near the start of this section.</p><p>For all that verbiage, the code itself is really pretty succinct. It’s significantly simpler than the first implementation I came up with!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b85dbb4a814792fef9bfd15921205f9a/href">https://medium.com/media/b85dbb4a814792fef9bfd15921205f9a/href</a></iframe><h3>Conclusion</h3><p>While I can’t say it’s necessarily the best, nor really always the most useful way to do things, it can help keep separate datastores and services from holding stale or orphaned data. And it doesn’t even use a library! You could even rewrite everything into a pure Promise based implementation and support old Node or old Browsers without transpilation!</p><p>Lastly, a few things were left undefined, such as what exactly a Composite Error is, since that wasn’t quite as important as how to handle coordinating all the Steps.</p><p>When I first implemented a Do+Undo type thing, I tried to cling as closely as I could to the Promise interface itself, which led to a somewhat convoluted implementation that didn’t play as well with async/await syntax and, even with normal Promise chaining, added extra noise. Needless to say, this purely Async Function based approach is much cleaner, both in use and in implementation.</p><h4>References and Inspirations</h4><ul><li><a href="https://github.com/lodash/lodash">https://github.com/lodash/lodash</a> Particularly <a href="https://github.com/lodash/lodash/wiki/FP-Guide">lodash/fp</a></li><li><a href="http://elm-lang.org/">http://elm-lang.org/</a> Not directly related to this, but as an ML style functional language it certainly had a lasting influence on my coding ideas.</li><li><a href="http://koajs.com/">http://koajs.com/</a> particularly writing middleware for it. And for Express and Redux, for that matter.</li><li><a href="https://www.npmjs.com/package/async">https://www.npmjs.com/package/async</a> What I used before async/await and Promise.all.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d8046c6f159" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Higher Order Functions and Redux Thunk]]></title>
            <link>https://medium.com/@joedski/higher-order-functions-and-redux-thunk-1e5983ae6b03?source=rss-b1946e4457d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e5983ae6b03</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[redux-thunk]]></category>
            <dc:creator><![CDATA[Joseph Sikorski]]></dc:creator>
            <pubDate>Sun, 24 Sep 2017 20:26:59 GMT</pubDate>
            <atom:updated>2017-09-24T20:26:59.462Z</atom:updated>
            <content:encoded><![CDATA[<p>Here I’ll show how I used higher order functions to break down thunks used with Redux Thunk into discrete, composible steps.</p><p>This assumes you’re reasonably comfortable with Redux and some integration with a UI library, as well as with treating functions as first class values.</p><h3>Abstraction</h3><p>I’ll start with an overview here, laying the groundwork for the rest of the examples.</p><h4>Thunks</h4><p>In Redux Thunk, you can dispatch a function that Redux will execute, injecting Redux’s output (getState) and input (dispatch). You can also give it a third optional argument to pass to thunks, with which you can inject app-specific context, but that will not be covered here.</p><p>So we have the thunk:</p><pre>Thunk :: (getState, dispatch) =&gt; mixed</pre><p>Usually, we want to do more than one thing, which means we need some way of passing in options or arguments to our thunk. This being Javascript, we can do that easily with another function, just closing over its arguments.</p><p>This gives us the usual unit of definition for a thunk, a Thunk Creator:</p><pre>ThunkCreator :: (...args) =&gt; Thunk<br>ThunkCreator :: (...args) =&gt; (getState, dispatch) =&gt; mixed</pre><p>For the project I worked on, I settled on using params and meta as the arguments to the ThunkCreator, in much the same way I parametrized my Action Creators with payload and meta, so I’ll assume those here:</p><pre>ThunkCreator :: (params, meta) =&gt; (getState, dispatch) =&gt; mixed</pre><p>We can see here then that a Thunk Creator is technically already a higher order function, it returns a new function closing over the variables params and meta.</p><p>I haven’t defined a result, so I’ll just do that right quick. Naturally, since we’re fetching something, we’re going to have a Promise. I don’t want to worry about uncaught rejections, so I’ll have both the error and result as possible resolutions to the Promise. If you want to use rejection, you should be able to adapt the code easily enough.</p><p>I end up with the full interface thus:</p><pre>ThunkCreator :: (params, meta) =&gt; (getState, dispatch) =&gt; { result, error }</pre><h4>Higher Order Functions and Thunks</h4><p>Or, more precisely, higher order thunk functions and thunk creators. It goes on to say that, when dealing with higher order functions, we take one further step back: Taking a ThunkCreator as an argument and returning another ThunkCreator as a value.</p><p>This gives us these two type definitions, both of which are synonymous:</p><pre>ThunkDecorator :: (ThunkCreator) =&gt; ThunkCreator<br>ThunkDecotaror :: (ThunkCreator) =&gt; (params, meta) =&gt; (getState, dispatch) =&gt; { result, error }</pre><blockquote>Aside: I’m using the term “Decorator” here loosely, to be analogous to how a Class modifier is usually called a Class Decorator. You could also refer to them as ThunkEnhancers.</blockquote><h4>Higher Order Functions and Compose</h4><p>This function signature means that composition of ThunkDecorators follows naturally:</p><pre>const otherDecorator = compose(<br>  decoratorA,<br>  decoratorB,<br>  decoratorC<br>);</pre><pre>const ultraThunkCreator = otherDecorator(boringThunkCreator);</pre><pre>// Or, for short:<br>const ultraThunkCreator = compose(<br>  decoratorA,<br>  decoratorB,<br>  decoratorC<br>)(boringThunkCreator);</pre><p>An interesting thing happens when using compose with higher order functions, though: The order of dataflow is both inwards and outwards!</p><p>In actuality, this inwards and outwards dataflow already happens, it is simply that the inwards part is not used when composing normal functions: The outer function is fed the argument, but all it does is pass it straight to the next function and wait for its result before modifying that and returning it, and the next function does the same thing by passing it to the next function still, on down to the last function, which finally evaluates just its own transformation on that input and returns its result, which the next function up transforms, and so on.</p><p>When composing higher order functions, however, because <em>the next function is the argument</em> to the first, you have an opportunity to define how the next function is called, including whether it’s even called at all! It also means you can transform the input before passing it on to the next function, then transform the output as usual. Notice that the result still goes through each function from back to front, just like with normal composition.</p><p>How this works will become clear in the examples through out this piece.</p><h4>Configurable Higher Order Functions</h4><p>The final thing to preface the rest of this piece with is the idea of configurable higher order functions, which are… functions returning higher order functions!</p><p>These can be loosely typed as:</p><pre>ConfigurableThunkDecorator :: (...options) =&gt; ThunkDecorator</pre><p>These are the most useful since they allow you to parametrize behavior. Their use is very similar to a normal ThunkDecorator, just you call them first so that they return their ThunkDecorator for composition:</p><pre>// instead of this:<br>const ultraThunkCreator = compose(<br>  decoratorA,<br>  decoratorB,<br>  decoratorC<br>)(boringThunkCreator);</pre><pre>// do this:<br>const ultraThunkCreator = compose(<br>  decoratorA(optionsA),<br>  decoratorB({ that: &#39;that&#39;, theOther: 4 }),<br>  decoratorC((params) =&gt; !!params.isHoopy),<br>)(boringThunkCreator);</pre><h3>Application</h3><h4>First: Requests</h4><p>The first thing we might like to do is actually request some data. I won’t go into much detail here, it’s about what you would expect: given certain params (and maybe meta?), request some resource. How you specify the mapping of params and meta to a request is largely irrelevant. I’ll give a simple example below. (I know this isn’t a Thunk Decorator but we’ll get there next…)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b771da97e3f560c679a9fcc7e9655e32/href">https://medium.com/media/b771da97e3f560c679a9fcc7e9655e32/href</a></iframe><p>… where resourceActions is a bundle of Action Creators. Note that here I have the meta here is passed as a payload prop, because it is meta for the thunk, not the action. Otherwise, this is standard async use of Redux Thunk.</p><p>Using this you could define an endpoint like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/518ca0e62370a326e22053f80d709607/href">https://medium.com/media/518ca0e62370a326e22053f80d709607/href</a></iframe><p>This would then be called like so, using React-Redux’s connect decorator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23187b0008c75bd2f7b1118aae28275a/href">https://medium.com/media/23187b0008c75bd2f7b1118aae28275a/href</a></iframe><p>Simple enough.</p><h4>Second: Arguments</h4><p>The most useful thing, I think, and most basic is being able to transform the params and meta, usually by just adding required or default params or meta. Using a higher order function here is much cleaner than just defining a one-off function each time: its name states what’s happening, and it preserves the (params, meta) argument contract rather than changing the shape every time.</p><p>Notice here how I do not need to define an anonymous function; the decorators do that for me, preserving the exposed interface!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e10d44fa62da2665d8dbe76e8dee8d16/href">https://medium.com/media/e10d44fa62da2665d8dbe76e8dee8d16/href</a></iframe><h4>Third: Chaining Thunks</h4><p>Admittedly, withParams (and defaultParams) isn’t the most exciting thing around, but it is a nice clean interface. Where things get interesting is when you want to uniformly chain thunks, combine resolutions, or even decide whether you want to dispatch another thunk at all.</p><p>The main use case for this sort of chaining is when dealing with services that, for some reason, require you to do a couple round trips to actually get the data you need. Now, you could just write it all out manually, thenning it together, but we don’t want to write that out unless we’re doing something weird.</p><p>In this case, I was expecting that the endpoint might return a successful but empty response, so I had to handle that case accordingly!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59111e42cd5fbc976201bcbc202fc927/href">https://medium.com/media/59111e42cd5fbc976201bcbc202fc927/href</a></iframe><h4>Fourth: Mapping Output</h4><p>Now we need to map the resolution! Since the thunk we’re concerned about is the myRelatedEndpoint one here, we’ll just decorate that one.</p><p>Again, this is a simple one, just instead of manipulating the inputs (params and meta) we manipulate the output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29f0f739696af5f0f60b1d1a54282450/href">https://medium.com/media/29f0f739696af5f0f60b1d1a54282450/href</a></iframe><p>Now, this isn’t quite the ideal, but it’s certainly closer. Some quick improvements could certainly be made:</p><ul><li>For one thing, by using withParams we’re polluting the params of myRelatedEndpoint. We should prefer to keep those clean since we don’t care about the original args at that point. Maybe something like mapParams which doesn’t automatically merge args…</li><li>This big blob of function calls can get pretty unwieldy. Sometimes you just need that in place when writing your mapDispatchToProps function, but in cases like this where it’s basically a “derived endpoint”, it’s worth trying to see how much you can take out into a separate endpoint thunk creator. Then you can import it and treat it just like any other thunk creator! Just like you treat myEndpoint! In fact, you can even compose it into other thunks…</li></ul><h3>The Beginning</h3><p>The functional composition approach isn’t the most straight forward, but it can lead to clean descriptive code, especially by encoding common usage patterns such as specifying default props. The biggest benefit in my opinion is the simultaneous enforcement and preservation of a given interface. All of these decorators expect thunk creators to take a given set of args and for the thunk those creators make to return a promise on a given object shape. Being able to compose behavior with that interface built in frees you from having to do that yourself!</p><p>That said, never let dogmatism get in the way of getting things done. I like this approach for the above reasons, and I certainly think it’s worth consideration, but you should only use it if it actually makes you more productive. (… Or if you’re bored and like writing functions?)</p><p>And if all this left your head spinning due to all the functions all the way down, don’t sweat it! Try to figure it out as best as you can, then move on and let things percolate.</p><h3>Resources</h3><p>These are some of the things that’ve inspired me to engage in this functional shenanigannery.</p><ul><li><a href="https://github.com/acdlite/recompose">https://github.com/acdlite/recompose</a> Small utility HOCs for React. It’s difficult to not use them everywhere.</li><li><a href="https://www.npmjs.com/package/function-tree">https://www.npmjs.com/package/function-tree</a> For when you need to go full declarative. What I did here was similar to function-tree, but function-tree operates on a context object which gets threaded through all the functions so it can handle more complex cases more easily. It also has great debugging facilities just like the rest of Cerebral!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e5983ae6b03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magical Initial AFpt, Auto Selection AI Servo AF Setting]]></title>
            <link>https://medium.com/@joedski/the-magical-initial-afpt-auto-selection-ai-servo-af-setting-14a9f301ff3c?source=rss-b1946e4457d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/14a9f301ff3c</guid>
            <category><![CDATA[canon]]></category>
            <category><![CDATA[canon-6d-ii]]></category>
            <category><![CDATA[photography]]></category>
            <dc:creator><![CDATA[Joseph Sikorski]]></dc:creator>
            <pubDate>Tue, 19 Sep 2017 00:07:07 GMT</pubDate>
            <atom:updated>2017-09-19T00:07:07.063Z</atom:updated>
            <content:encoded><![CDATA[<p>I just got a new Canon 6D II, and was reading about <a href="http://www.grantatkinson.com/blog/canon-6d-mark-ii-setup-for-wildlife-photography">how to set it up for wildlife photography</a> (and <a href="http://www.kenrockwell.com/canon/5d-mk-iii/users-guide/index.htm">how to setup a 5D Mk III for things</a>, a decent amount of which turned out could apply to the 6D II) and the one thing that continued to vex me as a newbie was the <em>Initial AFpt, Auto Selection AI Servo AF</em> setting. This setting is supposed to allow one to select a specific point for the AF system to start tracking things when AF is set to Auto Selection, the 4 outlines around all the AF points.</p><p>What threw me is that you can only actually see what point is the initial AF point <em>when the AF mode is set to AI Servo</em>! One might reasonably conclude that from the setting’s name, which explicitly mentions AI Servo, and thinking about it now it would be redundant to use that initial AF point setting during One Shot, but I didn’t see anything explicitly mention that you needed to be in AI Servo and so didn’t even consider that. It’s likely because if you’re interested in this setting, you’re also interested in setting things to AI Servo.</p><p>Once you discover this, of course, the difference between the two initial point options “Initial auto selection AF pt selected” and “Manual 1 pt AF pt” becomes clear.</p><ul><li>“Initial auto selection AF pt selected” means you can select a point yourself at which auto selection will start for acquiring a focus target to track, and this point is saved separately from the “Manual Selection: 1pt AF” point.</li><li>“Manual 1 pt AF pt” on the other hand means whatever point you select in “Manual Selection: 1 pt AF” mode will <em>also</em> be used as the initial AF point while in auto selection AF mode.</li></ul><p>And now I know.</p><p>Another interesting tidbit: Choosing “Manual 1pt AF pt” causes selecting a 1pt AF point or an initial auto selection area AF point to change all of the other AF area selections! So if you select a 1pt AF point in the right grouping of AF points in either spot AF, manual 1pt AF, or auto selection AF, it changes the zone AF and large zone AF area settings, too! Crazy. I suppose you don’t see that mentioned in the Atkinsons’ article because they disable all but the “Manual 1pt AF pt” and “Auto selection AF” areas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14a9f301ff3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memoization of Multi-Parametered Functions in JavaScript]]></title>
            <link>https://medium.com/@joedski/memoization-of-multi-parametered-functions-in-javascript-8508e89ba545?source=rss-b1946e4457d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8508e89ba545</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fun]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Joseph Sikorski]]></dc:creator>
            <pubDate>Fri, 14 Jul 2017 01:16:21 GMT</pubDate>
            <atom:updated>2017-07-17T22:58:48.009Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Update: After a bit of thought, I created a generalized memoizer than doesn’t require foreknowledge of the arity of the calculator function. See the gist at the bottom. I also created a similar memoizer that uses plain stores rather than memoizer functions if you have access to those.</blockquote><p>To start, this isn’t something I’m certain I’m going to use anywhere with real regularlity; perhaps as a quick measure while working to convert the current implementation of a project closer to the ideal.</p><p>I made this because when I’d started on one of my work projects, I didn’t have a clear understanding of how to properly use Reselect with React-Redux, selector factories, nor how to best make use of selectors to derive data and how to best employ memoization measures such as Reselect, and now trying to convert things to use those two libraries properly will be a very large ordeal indeed.</p><p>Still, it was an interesting problem to solve, I think, and one worth exploring. It is (maybe?) only partially solved, but solved for the case I was interested in: Memomization of a large number of derived entities that are extensions of a particular entity combined with several others.</p><h4>Typical Memoizers</h4><p>Taking a look at most memoizers out there, one usually sees memoizers that memoize on the first parameter and leave it at that. So far as I can tell, the reason for this is that managing 1-dimensional Maps is easy, n-dimensional Maps, not so much. Perhaps if JS had a native tuple type that might be possible, where an n-tuple could be used to treat a 1D Map as an nD Map, but alas it is not to be.</p><p>So just about any strategy for memoizing on more than one parameter is going to be less efficient and, indeed, most strategies I’ve seen so far involve serialization which is an interesting trade off indeed, or iterating over an array doing shallow comparisons on arrays of args. Surely there was a better way than this?</p><h3>Tiered Memoization</h3><p>After some thought, I came to the idea of combining closures with single-parameter memos to create a sort of tiered memoization. With the assumption that creation of functions and closures in JS cheaper than serialization, and that multiple equality checks is much cheaper than repeated serializations, I devised a simple strategy to break the memoization of multiple parameters into multiple memoizations of single parameters.</p><p>To start off, I made a few assumptions:</p><ul><li>The problem space I’m interested in assumes that, in the set of all sets of arguments to a given calculator, the first argument is unique across every set.</li><li>Any argument changing means a different result, as is expected for a memoization.</li></ul><p>As it would turn out, this solution neatly disregards the need for those assumptions, but I needed to start smaller.</p><p>To achieve the use of existing memos across multiple parameters, I essentially wrap the calculator function in a series of functions which each take one single parameter of that original function and memoize on that single parameter.</p><p>That is, I take a function like this:</p><pre>(a0, a1, a2, ...aN) =&gt; result</pre><p>And make it into a series of functions like this:</p><pre>a0 =&gt; a1 =&gt; a2 =&gt; ... aN =&gt; result</pre><p>Each function is memoized, and each subsequent function closes over the previous “partial result”s, meaning that we are able to effectively leverage existing single memos to cache the results of each argument application.</p><p>How does this work?</p><p>Note that in the second form of a0 =&gt; a1 =&gt; ... etc. it’s really a series of separate functions, each one returned by the previous. For added clarity, you can rewrite it to this identical form:</p><pre>a0 =&gt; (a1 =&gt; (a2 =&gt; ... (aN =&gt; result) ...))</pre><p>(ML folks: Hush, we’re still learning FP over here in JS land.)</p><p>The solution becomes obvious here: Each function from the first to the second-to-last caches the next function as its result! The last of course caches the actual result itself.</p><p>We thus get something like this:</p><pre>memoize(a0 =&gt; memoize(a1 =&gt; memoize(a2 =&gt; ... memoize(aN =&gt; calcResult(a0, a1, a2, ... aN)) ...))</pre><h4>Implementation</h4><p>This is easy enough to do manually, just nest each function and return a memoization on the next much like the sketch above, but what about the general case of N parameters?</p><p>I turned to a bit of recursion here to allow arbitrary nesting of these memoized selectors, and broke up the internal process into two steps:</p><ul><li>To start, we have two functions: applyValue and createApplier</li><li>applyValue has a signature a =&gt; (applyValue | result)</li><li>createApplier has a signature internalState =&gt; applyValue</li></ul><p>This then works by createApplier returning an applyValue, which itself will, if it is accepting the last argument, memoize the resulting calculation and if it is not, memoize the result of calling createApplier again thus caching the next applyValue.</p><p>What is internalState, though?</p><p>Since I’m building each next function recursively/iteratively rather than eagerly I need to carry the currently applied values forward, as well as have some way of knowing how many values are left before we call the actual result-calculator function. Those things constitute the internalState here.</p><p>This also conveniently enough shows how we kick the whole process off: Just call createApplier with the initial internalState (no values received, all N values remaining) to get back the first applyValue and feed in all the values from there.</p><p>In fact, this part is trivially implemented by reducing over each argument.</p><pre>const initialApplyValue =<br>  createApplier(calculateResult, memoizers, argCount, []);</pre><pre>const result = args.reduce(<br>  (applyValue, arg) =&gt; applyValue(arg),<br>  initialApplyValue,<br>)</pre><p>Where here, the exact signature I used for createApplier is (calculateResult, memoizers, expectedArgCount, collectedArgs) =&gt; applyValue .</p><p>What might createApplier look like, then?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/358a0b414b595d03ce8010339c2e24ed/href">https://medium.com/media/358a0b414b595d03ce8010339c2e24ed/href</a></iframe><p>Note that I passed in a list of memoizers because, in this case, I wanted to be able to use different strategies for each level. Particularly, given the first assumption where I stipulate that one of the arguments in each set of arguments is unique across all sets of arguments, the first argument specifically, I can use only one multi-value memo (WeakMap or LRU) and use quick single-memos for every other tier after that since I know that the first one is unique.</p><p>In fact, if one or more arguments are unique across all sets of arguments then you only need one multi-value memo at the very beginning, on one of the unique arguments! This is because if any of the arguments are unique, then you already know that each set of arguments is itself unique among all sets of arguments.</p><p>Conversely, however, if none of the arguments are unique, you may need multi-value memos for every tier! That is certainly one reason why creating memoized selectors per-instance with React-Redux is superior to this solution.</p><h3>All Together</h3><p>Here’s a gist with the final result of what I came up with. Because I’d intended to use it along side Reselect, I also have an enhancer that wraps around its createSelectorCreator function that makes it pass the selectors themselves as the first argument.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57a0654aa4609a5ea072db8cda7b880c/href">https://medium.com/media/57a0654aa4609a5ea072db8cda7b880c/href</a></iframe><p>An example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d04f12878afdb9ef77b737365e9faa5/href">https://medium.com/media/9d04f12878afdb9ef77b737365e9faa5/href</a></iframe><p>It seems to work!</p><h4>Performance?</h4><p>I currently have no idea how performant it is! I hope it’s at least nearly as performant as the slowest memoizer passed to it, though.</p><p>Note that if none of the arguments are unique across all sets of arguments you expect to call that selector with you’ll have to use multimemos for everything. I suppose WeakMaps may be an option if you expect to call it with a number of objects to compute derived entities or something, but you can’t use WeakMaps with non-Objects because, well, primitive values are refs.</p><h3>Other Thoughts</h3><p>Some finagling could probably be done to not require the expected number of args be passed in before hand and just memoize on what’s given, dynamically building the tiers. This could probably be done by just passing in values until we have no more than calling the last applyValue with 0 arguments instead of 1, or maybe each applyValue could return with a computeResult attached to it to apply the current list of values to the original computer function, and you just call that on the last applyValue returned. Perhaps I’ll take a whack at that for fun some time.</p><h4>Update: Did just that!</h4><p>Turned out not to be too difficult, a trivial variation of the first version. Like the first implementation, though, it’s probably not optimized, and likely is going to always be slower due to having to always assume we won’t know the number of args until call time. But, at least it doesn’t require finagling Reselect’s createSelectorCreator! I suppose if you were certain you were going to use only formal params in your functions, you could just use fn.length but in both of these cases I wrote it without that. It’s likely at least fast enough that it’s better than a React redraw, so, there’s that?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4facff4c3d6bdf6fe7a4983a465e5f8e/href">https://medium.com/media/4facff4c3d6bdf6fe7a4983a465e5f8e/href</a></iframe><h4>Update 2: Stores Only</h4><p>I also figured this same strategy could be used with stores themselves. Like the sub-memoizers ones described in the rest of this post, you have to ensure whatever store (or memoizer) you’re using for each arg can support what you’re throwing at it; for example, don’t use WeakMap for an argument position that might see primitives.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b55b27227ef23eca898840d2a30783a/href">https://medium.com/media/7b55b27227ef23eca898840d2a30783a/href</a></iframe><h4>False Starts</h4><p>I think it’s worth at least mentioning that I didn’t come to this solution in minutes, but rather across several days of now-and-again idle thought, and that the thinking that led to this current result was only the last bout over several weeks of picking it up and putting it down! I knew I’d needed to somehow reduce the number of arguments per memo, but wasn’t sure at first how to do it as the use of closures for some reason eluded me. Probably because I’m just a better programmer now. (And that’s why you should never stop learning!)</p><p>One idea I’d had was to start with a series of two argument functions which go something like (a, b) =&gt; ((a, b), c) =&gt; ((a, b, c), d) =&gt; ...but that still runs afoul of the original issue of multi-parameter memoization. It wasn’t until after exploration of a number of methods that I finally arrived on the a =&gt; memoize(b =&gt; memoize(c =&gt; ...)) method.</p><h4>Aside</h4><p>Going from the n-dimensional Maps for a moment, you could conceive of this as converting a set of coordinates in an n-D space into a series of mappings of 1-D spaces, where each additional argument constrains the target space by 1-D at a time until you built up to the specific point in the result space that those arguments act as coordinates to.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8508e89ba545" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript: Redux: Dispatching Multiple Actions]]></title>
            <link>https://medium.com/@joedski/javascript-redux-dispatching-multiple-actions-4b74831cbb?source=rss-b1946e4457d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b74831cbb</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[newbie]]></category>
            <category><![CDATA[beginner-javascript]]></category>
            <dc:creator><![CDATA[Joseph Sikorski]]></dc:creator>
            <pubDate>Sun, 28 May 2017 21:29:59 GMT</pubDate>
            <atom:updated>2017-05-28T21:29:59.745Z</atom:updated>
            <content:encoded><![CDATA[<p>Tiny musing for self amusement. And hopefully some edification?</p><p>Probably one of the first things anyone starting out on Redux wonders is, can you dispatch multiple actions?</p><p>The answer of course is, yes, just either call dispatch multiple times or iterate dispatch over an array. Usually, though, if you’re dispatching multiple actions like that, it’s a sign that you might want to look into creating yet another action to better encode the intent behind the cause of all those other actions.</p><p>But, what if your action is a strict combination of those other actions? Well, you could just create a meta-action which takes those other actions and returns a new single one representing them. Behind the scenes, of course, it’d still just iterate over the actions, dispatching them in turn.</p><p>There’s actually two ways we could go about this, both of them essentially equivalent in function:</p><ol><li>Use <a href="https://github.com/gaearon/redux-thunk">Redux Thunk</a></li><li>Create our own <a href="http://redux.js.org/docs/advanced/Middleware.html">middleware</a></li></ol><h4>Using Redux Thunk</h4><p>Note: I’m presuming you know how to <a href="https://github.com/gaearon/redux-thunk#installation">setup Redux Thunk’s middleware</a> so I will be skipping that part. I’m also presuming you’re at least passingly familiar with some <a href="https://babeljs.io/learn-es2015/">ES6 features</a> such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a>.</p><p>How would this look with a Thunk Action Creator, then?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/461effdcd60edc3e7beaa66186abbc37/href">https://medium.com/media/461effdcd60edc3e7beaa66186abbc37/href</a></iframe><h4>Creating Our Own Middleware</h4><p>Note: I’m presuming you know how to <a href="http://redux.js.org/docs/api/applyMiddleware.html">add middleware to your Redux Store</a>, so I’m skipping that part.</p><p>What might a custom middleware look like?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88a8a03744b10051853c908acfd5a32a/href">https://medium.com/media/88a8a03744b10051853c908acfd5a32a/href</a></iframe><h4>Creating Our Own Middleware: Variation</h4><p>As a variation on the above, you could just say “Screw it, I’mma teach Redux how to handle arrays!”, in much the same manner Redux Thunk teaches Redux how to handle Functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47800af65dc6035a3d813d404790ec7c/href">https://medium.com/media/47800af65dc6035a3d813d404790ec7c/href</a></iframe><h3>Result</h3><p>The effective result is the same: you can now dispatch multiple actions from one dispatch call.</p><p>Here we have two examples using <a href="https://github.com/reactjs/react-redux">React Redux</a>’s <a href="https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options">connect decorator</a> and <a href="https://facebook.github.io/react/docs/introducing-jsx.html">React’s JSX</a>, the first using the multiAction action creator, the second using just an array.</p><p>Note: These examples use a <a href="https://facebook.github.io/react/docs/components-and-props.html">Stateless Functional Component</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6df2795dc0cbac8039932ca32c3c6562/href">https://medium.com/media/6df2795dc0cbac8039932ca32c3c6562/href</a></iframe><h4>Bonus!</h4><p>As mentioned at the very beginning, you could also just save a new action creator which explicitly encodes this combination of actions as a new one…</p><pre>// multiAction style!<br>const doAllTheThings = () =&gt; multiAction([<br>  doThisThing(),<br>  doThatThing({ computer: &#39;over&#39; }),<br>  doTheOtherThing(&#39;foo&#39;),<br>]);</pre><pre>// array style!<br>const doAllTheThings = () =&gt; [<br>  doThisThing(),<br>  doThatThing({ computer: &#39;over&#39; }),<br>  doTheOtherThing(&#39;foo&#39;),<br>];</pre><p>Then in connect…</p><pre>connect(<br>  null,<br>  dispatch =&gt; ({<br>    doAllTheThings: () =&gt; dispatch(doAllTheThings()),<br>  }),<br>)(...);</pre><p>Nice.</p><p>As an added bonus, if it turns out later that just using an array of actions like that was not quite correct, or you need to change which actions are being used there, you how have that already decoupled from the view for easy refactor. Very nice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b74831cbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>