Strategy pattern for just one function - javascript

The strategy pattern is software a design pattern to select an algorithm at runtime. See this javascript implementation for reference.
See the linked page, how the example use different classes at runtime. But, what about if you just want to select one function? Is it worth encapsulate those functions in classes? Or just select the function to use, like in the next snipped:
function getRandomThing() {
return Math.floor(Math.random() * thingsCount);
}
function getNextThing() {
return currentThing++ % thingsCount;
}
currentGetThing = getNextThing
currentGetThing()
Is this solution correct? It works, but currentGetThing = getNextThing sounds a bit C-liked for me.

Just select the function directly.
Is it worth encapsulate those functions in classes?
No. It's hardly ever worth to encapsulate anything in a class when you can do without - that many other languages cannot do without and require classes for everything should not affect your choice in JavaScript.
Also don't forget that functions already are objects in JavaScript, they're instances of the Function class. If you absolutely want to define an interface for them, just go for duck-typing their call method.

I believe you lack the Context, the part of your code which uses the algorithm and where you want the algorithm to be replaced with another one. Take a look at the UML class diagram of the Strategy pattern to find that the Context is a vital part of the pattern.
In statically-typed OO implementations of the pattern, the context uses the abstraction of the strategy and the abstraction is either an interface or an abstract class. However, passing just a function would of course work, too. It's more your style of the implementation rather than a requirement to implement it in any specific way.
What is missing in your snipped then is the context, what possibly raises your doubts about the C-like style. Just let the strategy function be passed to the context, just like you would pass the strategy object to a context in an OO-like language.
var thingsCount = 5;
var currentThing = 0;
function getRandomThing() {
return Math.floor(Math.random() * thingsCount);
}
function getNextThing() {
return currentThing++ % thingsCount;
}
// strategy passed as a function
function context(strategy) {
var result = strategy();
console.log(result);
}
// call the context with different strategies
context(getNextThing);
context(getRandomThing);

Related

How is injecting an impure function different from calling it?

I am reading a book where it says one way to handle impure functions is to inject them into the function instead of calling it like the example below.
normal function call:
const getRandomFileName = (fileExtension = "") => {
...
for (let i = 0; i < NAME_LENGTH; i++) {
namePart[i] = getRandomLetter();
}
...
};
inject and then function call:
const getRandomFileName2 = (fileExtension = "", randomLetterFunc = getRandomLetter) => {
const NAME_LENGTH = 12;
let namePart = new Array(NAME_LENGTH);
for (let i = 0; i < NAME_LENGTH; i++) {
namePart[i] = randomLetterFunc();
}
return namePart.join("") + fileExtension;
};
The author says such injections could be helpful when we are trying to test the function, as we can pass a function we know the result of, to the original function to get a more predictable solution.
Is there any difference between the above two functions in terms of being pure as I understand the second function is still impure even after getting injected?
An impure function is just a function that contains one or more side effects that are not disenable from the given inputs.
That is if it mutates data outside of its scope and does not predictably produce the same output for the same input.
In the first example NAME_LENGTH is defined outside the scope of the function - so if that value changes the behaviour of getRandomFileName also changes - even if we supply the same fileExtension each time. Likewise, getRandomLetter is defined outside the scope - and almost certainly produces random output - so would be inherently impure.
In second example everything is referenced in the scope of the function or is passed to it or defined in it. This means that it could be pure - but isn't necessarily. Again this is because some functions are inherently impure - so it would depend on how randomLetterFunc is defined.
If we called it with
getRandomFileName2('test', () => 'a');
...then it would be pure - because every time we called it we would get the same result.
On the other hand if we called it with
getRandomFileName2(
'test',
() => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(Math.floor(25 * Math.random()))
);
It would be impure, because calling it each time would give a different result.
There's more than one thing at stake here. At one level, as Fraser's answer explains, assuming that getRandomLetter is impure (by being nondeterministic), then getRandomFileName also is.
At least, by making getRandomFileName2 a higher-order function, you at least give it the opportunity to be a pure function. Assuming that getRandomFileName2 performs no other impure action, if you pass it a pure function, it will, itself, transitively, be pure.
If you pass it an impure function, it will also, transitively, be impure.
Giving a function an opportunity to be pure can be useful for testing, but doesn't imply that the design is functional. You can also use dependency injection and Test Doubles to make objects deterministic, but that doesn't make them functional.
In most languages, including JavaScript, you can't get any guarantees from functions as first-class values. A function of a particular 'shape' (type) can be pure or impure, and you can check this neither at compile time nor at run time.
In Haskell, on the other hand, you can explicitly declare whether a function is pure or impure. In order to even have the option of calling an impure action, a function must itself be declared impure.
Thus, the opportunity to be impure must be declared at compile time. Even if you pass a pure 'implementation' of an impure type, the receiving, higher-order function still looks impure.
While something like described in the OP would be technically possible in Haskell, it would make everything impure, so it wouldn't be the way you go about it.
What you do instead depends on circumstances and requirements. In the OP, it looks as though you need exactly 12 random values. Instead of passing an impure action as an argument, you might instead generate 12 random values in the 'impure shell' of the program, and pass those values to a function that can then remain pure.
There's more at stake than just testing. While testability is nice, the design suggested in the OP will most certainly be impure 'in production' (i.e. when composed with a proper random value generator).
Impure actions are harder to understand, and their interactions can be surprising. Pure functions, on the other hand, are referentially transparent, and referential transparency fits in your head.
It'd be a good idea to have as a goal pure functions whenever possible. The proposed getRandomFileName2 is unlikely to be pure when composed with a 'real' random value generator, so a more functional design is warranted.
Anything that contains random (or Date or stuff like that). Will be considered impure and hard to test because what it returns doesn't strictly depends on its inputs (always different). However, if the random part of the function is injected, the function can be made "pure" in the test suite by replacing whatever injected randomness with something predictable.
function getRandomFileName(fileExtension = "", randomLetterFunc = getRandomLetter) {}
can be tested by calling it with a predictable "getLetter" function instead of a random one:
getRandomFileName("", predictableLetterFunc)

Is it possible to give a type/class to JavaScript functions?

I wonder if it's possible to give a a type/class to JavaScript functions.
Of course, the Object class/type of function is 'Function/function'.
http://bonsaiden.github.io/JavaScript-Garden/#types.typeof
However, in my project, somehow I want to define class for function to group them.
It's similar concept HTML/CSS DOM element class.
I have a function which args is a function, and I want to distinguish which type or class of function is passed to the function.
It does not work with any object method, just a function, but it can be distinguished like obj.hasOwnProperty('someClass') .
I just wonder if there's smart way, if you think impossible, please insist so.
Thanks.
PS. I do not why someone vote -1 and to close this question.
This is the matter of reflection of Javascript. It's ok if find some reflection factor of JS is limited. and I think it's not wise to avoid to make it clear that something is impossible in a certain language.
A function is an object. You can add your own custom properties to any function. So, if you want to set your own type on several different functions so you can test for that, you can just add the same custom property (with different values assigned to it) to each of those functions.
function myFunc1() {}
myFunc1.myType = "whatever1";
function myFunc2() {}
myFunc2.myType = "whatever2";
function myFunc3() {}
myFunc3.myType = "whatever3";
function callMe(cb) {
if (cb.myType === "whatever1") {
// code here
} else if (...) {
// code here
}
}
callMe(myFunc1);
Note, this is a bit unusual and if you explained the actual problem you were trying to solve, there is probably a more common design pattern that might help you.
#jfriend00 has suggested the answer.
FYI, functions are objects so they can have your own custom properties so you could make your own custom property.
He's right, so to add a class/property to any functions, simply do
var myFunction = function(foo){...};
myFunction['someClass'] = true;
//To distinguish
if (someFunction.hasOwnProperty('someClass'))
{
console.log('someFunction is someClass');
}

Examples of practical javascript object oriented design patterns

What object oriented design patterns do you use in your application's javascript, and why?
Feel free to post code, even if there is no formal design pattern attached to it.
I have written plenty of javascript, but I have not applied much object orientated patterns to what I am doing, and I am sure i am missing a lot.
The following are three popular JavaScript patterns. These happen to be easily implementable because of closures:
The Module Pattern - Example (and made popular) by Eric Miraglia
Memoization - Example by Oliver Steele
Currying - Example by Dustin Diaz
You may also want to check out:
Pro JavaScript Design Patterns by Ross Harmes and Dustin Diaz
The following is a Google I/O talk from 2008 presented by Diaz, where he discusses some topics from his book:
Google I/O 2008 - Design Patterns in an Expressive Language
Inheritance
I use a notation for inheritance that is based on ExtJS 3, which I find works pretty close to emulating classical inheritance in Java. It basically runs as follows:
// Create an 'Animal' class by extending
// the 'Object' class with our magic method
var Animal = Object.extend(Object, {
move : function() {alert('moving...');}
});
// Create a 'Dog' class that extends 'Animal'
var Dog = Object.extend(Animal, {
bark : function() {alert('woof');}
});
// Instantiate Lassie
var lassie = new Dog();
// She can move and bark!
lassie.move();
lassie.bark();
Namespaces
I also agree with Eric Miraglia on sticking to namespaces so the code above should be run within its own context outside the window object, this is critical if you intend your code to run as one of many concurrent frameworks / libraries executing in the browser window.
This means that the only way to the window object is via your own namespace / module object:
// Create a namespace / module for your project
window.MyModule = {};
// Commence scope to prevent littering
// the window object with unwanted variables
(function() {
var Animal = window.MyModule.Animal = Object.extend(Object, {
move: function() {alert('moving...');}
});
// .. more code
})();
Interfaces
You can also make use of more advances OOP constructs such as interfaces to enhance your application design. My approach to these is to enhance the Function.prototype in order to get a notation along these lines:
var Dog = Object.extend(Animal, {
bark: function() {
alert('woof');
}
// more methods ..
}).implement(Mammal, Carnivore);
OO Patterns
As for 'Patterns' in the Java sense, I've only found use for the Singleton pattern (great for caching) and the Observer pattern for event-driven functionality such as assigning some actions when a user clicks on a button.
An example of utilising the Observer Pattern would be:
// Instantiate object
var lassie = new Animal('Lassie');
// Register listener
lassie.on('eat', function(food) {
this.food += food;
});
// Feed lassie by triggering listener
$('#feeding-button').click(function() {
var food = prompt('How many food units should we give lassie?');
lassie.trigger('eat', [food]);
alert('Lassie has already eaten ' + lassie.food + ' units');
});
And thats just a couple of tricks in my bag of OO JS, hope they are useful to you.
I recommend if you intend to go down this road that you read Douglas Crockfords Javascript: the Good Parts. Its a brilliant book for this stuff.
I am a fan of the Module Pattern. It's a way of implementing extensible, non-dependent (most of the time) frameworks.
Example:
The framework, Q, is defined like this:
var Q = {};
To add a function:
Q.test = function(){};
These two lines of code are used together to form modules. The idea behind modules is that they all extend some base framework, in this case Q, but are not reliant on each other (if designed correctly) and can be included in any order.
In a module, you first create the framework object if it does not exist (which is an example of the Singleton pattern):
if (!Q)
var Q = {};
Q.myFunction = function(){};
That way, you can have multiple modules (like the one above) in separate files, and include them in any order. Any one of them will create the framework object, and then extend it. No manual need to check if the framework exists. Then, to check if a module/function exists in custom code:
if (Q.myFunction)
Q.myFunction();
else
// Use a different approach/method
The singleton pattern is often very helpful for 'encapsulation' and organization stuff. You can even change accesibility.
var myInstance = {
method1: function () {
// ...
},
method2: function () {
// ...
}
};
cleanest way to implement a singleton in javascript
I really like jquery's method chaining pattern, allowing you to call several methods on one object. It makes it really easy to perform several operations in a single line of code.
Example:
$('#nav').click(function() {
$(this).css('color','#f00').fadeOut();
});
I really like the Decorator pattern with jQuery plugins. Rather than modifying plugins to meet your needs, write a custom plugin that just forwards requests and adds additional parameters and functionality.
For example, if you need to pass a set of default arguments around all the time, and you need slightly-different behavior that ties into business logic, write a plugin that does whatever pre and post work is necessary to suit your needs and passes your default arguments if those particular arguments aren't specified.
The main benefit of this is that you can update your libraries and not worry about porting library changes. Your code might break, but there's at least the chance that it won't.
One of useful patterns in javascript world is chaining pattern which is made popular by LINQ at first place, and also is used in jQuery.
this pattern enables us to call different methods of a class in chaining manner.
the main structure of this pattern would be as
var Calaculator = function (init) {
var result = 0;
this.add = function (x) { result += (init + x); return this; };
this.sub = function (x) { result += (init - x); return this; };
this.mul = function (x) { result += (init * x); return this; };
this.div = function (x) { result += (init / x); return this; };
this.equals = function (callback) {
callback(result);
}
return this;
};
new Calaculator(0)
.add(10)
.mul(2)
.sub(5)
.div(3)
.equals(function (result) {
console.log(result);
});
the key idea of this pattern is this key word, which makes possible accessing to other public member of Calculator fucntion.

How is a functional programming-based JavaScript app laid out?

I've been working with node.js for a while on a chat app (I know, very original, but I figured it'd be a good learning project). Underscore.js provides a lot of functional programming concepts which look interesting, so I'd like to understand how a functional program in JavaScript would be setup.
From my understanding of functional programming (which may be wrong), the whole idea is to avoid side effects, which are basically having a function which updates another variable outside of the function so something like
var external;
function foo() {
external = 'bar';
}
foo();
would be creating a side effect, correct? So as a general rule, you want to avoid disturbing variables in the global scope.
Ok, so how does that work when you're dealing with objects and what not? For example, a lot of times, I'll have a constructor and an init method that initializes the object, like so:
var Foo = function(initVars) {
this.init(initVars);
}
Foo.prototype.init = function(initVars) {
this.bar1 = initVars['bar1'];
this.bar2 = initVars['bar2'];
//....
}
var myFoo = new Foo({'bar1': '1', 'bar2': '2'});
So my init method is intentionally causing side effects, but what would be a functional way to handle the same sort of situation?
Also, if anyone could point me to either a Python or JavaScript source code of a program that tries to be as functional as possible, that would also be much appreciated. I feel like I'm close to "getting it", but I'm just not quite there. Mainly I'm interested in how functional programming works with traditional OOP classes concept (or does away with it for something different if that's the case).
You should read this question:
Javascript as a functional language
There are lots of useful links, including:
Use functional programming techniques to write elegant JavaScript
The Little JavaScripter
Higher-Order JavaScript
Eloquent JavaScript, Chapter 6: Functional Programming
Now, for my opinion. A lot of people misunderstand JavaScript, possibly because its syntax looks like most other programming languages (where Lisp/Haskell/OCaml look completely different). JavaScript is not object-oriented, it is actually a prototype-based language. It doesn't have classes or classical inheritance so shouldn't really be compared to Java or C++.
JavaScript can be better compared to a Lisp; it has closures and first-class functions. Using them you can create other functional programming techniques, such as partial application (currying).
Let's take an example (using sys.puts from node.js):
var external;
function foo() {
external = Math.random() * 1000;
}
foo();
sys.puts(external);
To get rid of global side effects, we can wrap it in a closure:
(function() {
var external;
function foo() {
external = Math.random() * 1000;
}
foo();
sys.puts(external);
})();
Notice that we can't actually do anything with external or foo outside of the scope. They're completely wrapped up in their own closure, untouchable.
Now, to get rid of the external side-effect:
(function() {
function foo() {
return Math.random() * 1000;
}
sys.puts(foo());
})();
In the end, the example is not purely-functional because it can't be. Using a random number reads from the global state (to get a seed) and printing to the console is a side-effect.
I also want to point out that mixing functional programming with objects is perfectly fine. Take this for example:
var Square = function(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
};
function getArea(square) {
return square.w * square.h;
}
function sum(values) {
var total = 0;
values.forEach(function(value) {
total += value;
});
return total;
}
sys.puts(sum([new Square(0, 0, 10, 10), new Square(5, 2, 30, 50), new Square(100, 40, 20, 19)].map(function(square) {
return getArea(square);
})));
As you can see, using objects in a functional language can be just fine. Some Lisps even have things called property lists which can be thought of as objects.
The real trick to using objects in a functional style is to make sure that you don't rely on their side effects but instead treat them as immutable. An easy way is whenever you want to change a property, just create a new object with the new details and pass that one along, instead (this is the approach often used in Clojure and Haskell).
I strongly believe that functional aspects can be very useful in JavaScript but ultimately, you should use whatever makes the code more readable and what works for you.
You have to understand that functional programming and object oriented programming are somewhat antithetical to each other. It's not possible to both be purely functional and purely object oriented.
Functional programming is all about stateless computations. Object oriented programming is all about state transitions. (Paraphasing this. Hopefully not too badly)
JavaScript is more object oriented than it is functional. Which means that if you want to program in a purely functional style, you have to forego large parts of the language. Specifically all the object orient parts.
If you are willing to be more pragmatic about it, there are some inspirations from the purely functional world that you could use.
I try to adhere to the following rules:
Functions that perform computations should not alter state. And functions that alter state should not perform computations. Also, functions that alter state should alter as little state as possible. The goal is to have lots of little functions that only do one thing. Then, if you need to do anything big, you compose a bunch of little functions to do what you need.
There are a number of benefits to be gained from following these rules:
Ease of reuse. The longer and more complex a function is, the more specialized it also is, and therefore the less likely it is that it can be reused. The reverse implication is that shorter functions tend to more generic and therefore easier to reuse.
Reliability of code. It is easier to reason about correctness of the code if it is less complex.
It is easier to test functions when they do only one thing. That way there are fewer special cases to test.
Update:
Incorporated suggestion from comment.
Update 2:
Added some useful links.
I think, http://documentcloud.github.com/underscore/ should be nice fit for what you need - it provides the most important higher-order functions for functional programming and does not has client-side functions for DOM manipulation which you don't need for server side. Though I don't have experience with it.
As a side note: IMHO primary feature of functional programming is Referential transparency of a function - function result depends only on its parameters - function does not depend on changes on other objects and does not introduce any change except its result value. It makes it easy to reason about program's correctness and very valuable for implementing of predictable multi-threading (if relevant). Though JavaScript is not the bet language for FP - I expect immutable data structures to be very expensive performance-wise to use.
So 2 things to point out ,
In your first example your variable would not be leaking into the global area and is the way it should be done , try to never use variables without declaring them i.e. test = 'data' would cause data to leak into the global area.
Your second example is correct as well , bar1 and bar2 would only be declared on the Foo object.
Things to keep in mind try not to overuse prototyping since it applies to every object that you create , this could be extremely memory intensive depending on how complex your objects are.
If you are looking for a app development framework , have a look at ExtJs. Personally I think it would fit perfectly into the model you are trying to develop against. Just keep in mind how their licensing model works before getting heavily invested in it.

Is "Partial Function Application" a misnomer in the context of Javascript?

A friend of mine and I were having a discussion regarding currying and partial function application in Javascript, and we came to very different conclusions as to whether either were achievable. I came up with this implementation of Function.prototype.curry, which was the basis of our discussion:
Function.prototype.curry = function() {
if (!arguments.length) return this;
var args = Array.prototype.slice.apply(arguments);
var mmm_curry = this, args;
return function() {
var inner_args = Array.prototype.slice.apply(arguments);
return mmm_curry.apply(this, args.concat(inner_args));
}
}
Which is used as follows:
var vindaloo = function(a, b) {
return (a + b);
}
var karahi = vindaloo.curry(1);
var masala = karahi(2);
var gulai = karahi(3);
print(masala);
print(other);
The output of which is as follows in Spidermonkey:
$ js curry.js
3
4
His opinion was that since the Javascript function primitive does not natively support "partial function application", it's completely wrong to refer to the function bound to the variable karahi as partially applied. His argument was that when the vindaloo function is curried, the function itself is completely applied and a closure is returned, not a "partially applied function".
Now, my opinion is that while Javascript itself does not provide support for partial application in its' function primitives (unlike say, ML or Haskell), that doesn't mean you can't create a higher order function of the language which is capable of encapsulating concept of a partially applied function. Also, despite being "applied", the scope of the function is still bound to the closure returned by it causing it to remain "partially applied".
Which is correct?
Technically you're creating a brand new function that calls the original function. So if my understanding of partially applied functions is correct, this is not a partially applied function. A partially applied function would be closer to this (note that this isn't a general solution):
vindaloo.curry = function(a) {
return function(b) {
return a + b;
};
};
IIUC, this still wouldn't be a partially applied function. But it's closer. A true partially applied function would actually look like this if you can examine the code:
function karahi(b) {
return 1 + b;
};
So, technically, your original method is just returning a function bound within a closure. The only way I can think of to truly partially apply a function in JavaScript would be to parse the function, apply the changes, and then run it through an eval().
However, your solution is a good practical application of the concept to JavaScript, so practically speaking accomplishes the goal, even if it is not technically exact.
I think it's perfectly OK to talk about partial function application
in JavaScript - if it works like partial application, then it must
be one. How else would you name it?
How your curry function accomplishes his goal is just an implementation
detail. In a similar way we could have partial application in the ECMAScript spec,
but when IE would then implement it just as you did, you would have
no way to find out.
The technical details don't matter to me - if the semantics remain the same and, for all intents and purposes, the function acts as if it were really a partially-applied function, who cares?
I used to be as academic about things, but worrying about such particulars doesn't get real work done in the end.
Personally, I use MochiKit; it has a nice partial() function which assists in the creation of such. I loves it.
You should check out Curried JavaScript Functions. I haven't completely wrapped my head around his curry function, but it might have your answer.
Edit: I would agree with your assessment, however.
His opinion was that since the Javascript function primitive does not natively support "partial function application"
You can do currying in ES6 pretty elegantly:
> const add = a => b => a + b
> const add10 = add(10)
> [1,2,3].map(add10)
[ 11, 12, 13 ]

Categories