Created
February 19, 2017 02:13
-
-
Save idettman/2b7cebd9b1a89e3ef3f02f047c866810 to your computer and use it in GitHub Desktop.
JavaScript Named Curry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function namedCurry(source_fn, arg_order){ | |
| function receiver( received_values, n_received, defaults ){ | |
| received_values = (received_values || []).slice() | |
| n_received = n_received || 0 | |
| Object.keys(defaults).forEach(function( input_arg ){ | |
| var value = defaults[ input_arg ] | |
| var required_index = arg_order.indexOf( input_arg ) | |
| var is_known_argument = required_index > -1 | |
| var existing_value = received_values[required_index] | |
| if( is_known_argument ){ | |
| if( typeof existing_value == "undefined" ){ | |
| n_received++ | |
| } | |
| received_values[required_index] = value; | |
| } | |
| }) | |
| if( n_received >= arg_order.length ){ | |
| return source_fn.apply(null, received_values ) | |
| } else { | |
| return receiver.bind( null, received_values, n_received ) | |
| } | |
| } | |
| return receiver.bind(null, null, 0) | |
| } | |
| // Example usage | |
| // The original render function with positional arguments. | |
| function render(controller, view, renderImmediately ){ | |
| console.log("Rendering",view,"as part of a",controller,"controller", renderImmediately ? "(now)" : "(later)" ) | |
| } | |
| // A curried-options object style version of the original render function. | |
| // Notice the argument names are different to the source code. | |
| var namedRender = namedCurry(render, ["ctrl", "view", "immediate"]) | |
| //Creating some preconfigured functions for different areas of the site. | |
| //This function is waiting on the `immediate` parameter before being invoked. | |
| var modal_signup = namedRender({ | |
| ctrl: "modal", | |
| view: "signup form" | |
| }) | |
| //This function is waiting for the `view` parameter before being invoked. | |
| var sidebar_later = namedRender({ | |
| ctrl: "sidebar", | |
| immediate: false | |
| }) | |
| //Invoking the signup modal _immediately_ | |
| modal_signup({ | |
| immediate: true | |
| }) | |
| //Invoking the signup modal _later_ | |
| modal_signup({ | |
| immediate: false | |
| }) | |
| //Invoking the sidebar with some navigation icons _later_ | |
| sidebar_later({ | |
| view: "naviagation-icons" | |
| }) | |
| //Invoking the sidebar_later as above, but we are overwriting the immediate property at call time. | |
| sidebar_later({ | |
| immediate: true, //you can overwrite existing properties | |
| view: "naviagation-icons" | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment