when we do not want to break the immutability of an object, we will create a copy of it each time we will call a mutator method like a setter method, or any method that will change any property in the object.
Now the question is really about naming conventions: since the setter is not mutating the object any longer, rather it creates a copy and returns a copy of the object, so what should we name it?
here is an example
weatherData: function (obj) {
let value_Copy = { ...obj }
const getValue = () => value_Copy
const setValue = (_value) => weatherData(_value) // this is not a mutator, it is just returns a copy with new arguments
return { getValue, setValue }
}
thanks in advance
I would give the new value a meaningful name of its own. Naturally you are performing an "update" operation on the original data for a purpose. My name for the new variable would describe why it was updated, because that will make the code more readable.
Compare
const weatherToday = weatherData(someData)
const weatherTomorrow = weatherToday.setValue('temperature', 23)
with
const weather = weatherData(someData)
const weather2 = weatherData.setValue('temperature', 23)
The former shows the reader what the new data is for. The second will very quickly become unreadable.
I'm not sure what you mean by "Most functions need to include a setter function".
You also don't say what programming language you are working with.
In a pure functional approach, there is no such thing as a "setter", nor a "mutator". Those are generally object-oriented concepts.
If you are working in an object-oriented language, e.g. Java, and trying to work in a functional style, then you are likely to have a mix of object-oriented and functional styles, so I suppose the dividing line between the two would be up to you.
Related
In JavaScript consider I am trying to append a new value and return it.
I have below example regarding overriding parameter value
The below function receives a string value as param and overriding the param with new value and returning it.
function test(value) {
value = value + "hi";
return value;
}
console.log(test("Hello"));
The below function receives a string value as param. I would like to append a new value and return it. So I assigned value to a local variable and then appended strong to a new variable and returning it.
function test(value) {
let temp = value;
temp = value + "hi";
return temp;
}
console.log(test("Hello"));
I am calling it and passing value
test(“Hello”);
Which one is recommended from above?
It's purely a matter of style. Some people think you should leave parameter values alone, others think it's fine to change them.¹
From a practical perspective, it doesn't cause any harm. That is, there is no hidden side-effect to doing so. In particular, since JavaScript is purely pass-by-value, reassigning the parameter can't have any effect on whatever argument was used to fill in that parameter:
function test(value) {
value = value + "hi";
return value;
}
let a = "let's say ";
let b = test(a);
console.log(b); // "let's say hi"
console.log(a === b); // false, `a` was not modified
Your version with temp can be simpler, though:
function test(value) {
let temp = value + "hi";
return temp;
}
(or even
function test(value) {
return value + "hi";
}
but I figure it's highly simplified for the question.)
¹ (I happen to be in the latter camp, but that's neither here nor there.)
Yes, this is not at all wrong and is often done by many programmers across many languages. It is a common practice.
You can use it in cases where you want to use the parameter value inside the function but after making certain modifications to it.
For example, I might want to add two numbers using a function add(a, b) where a and b can be strings or integers or floats.
But just to be sure about it, I can define the add function in the following way:
function add(a,b) {
a = parseFloat(a);
b = parseFloat(b);
return a + b;
}
and this is perfectly fine. This way I can be always sure that there will be no exceptions thrown or in case parameters were passed as strings, it doesn't returns 12 (if I said add(1,2)) when really it should have been 3.
By making parameter overriding a common practice and incorporating it into your coding style, you spare the browser from creating or defining new variables just to modify those variable values. This might not mean much in small applications, but in large scale heavy applications, it might make a noticeable difference especially on low end devices.
The short answer is: it's only a matter of style.
However, this isn't always right. When passing objects, they will be passed by reference, meaning that every change you'll make to the parameter will affect the original object:
const obj = {originalValue: true};
function modifyObject(input) {
input.originalValue = false; // The change happens here
return input; // So it will take place regardless of this line
}
console.log('before:', obj);
modifyObject(obj); // See? we don't even retrieve the return value
console.log('after:', obj);
If we were talking about Java, then creating a new variable would be good practice. As there is something called the Garbage Collector that collects unused variables, etc. and discards them. So keeping a link to the original variable wouldn't allow the collector to discard the variable. (I read this somewhere, but some people said to me it doesn't really work this way, so read more about this online if you want)
In JavaScript, however, it doesn't really matter. It depends on you. Your style. It also depends on the situation as it can be useful sometimes. But really it doesn't really matter. Do as you like.
If you want to simplify it you can do as #T.JCrowder said:
function test(value){
return value+ “hi”;
}
That's about it.
Using ES6 Template literals
function test(value){
return `${value} hi`;
}
I am trying to understand the ways of using functional style in JavaScript in practice. I've created a simple set of functions to process a string, but I feel I am doing it conceptually wrong because it looks just like imperative style, even though I don't mutate input and don't change state of the app inside the functions.
Here is how it looks:
var LineParser = require('../modules/LineParser');
var inputLine = 'A line with multiple spaces';
var outputLine = LineParser().formatSpaces(inputLine);
// 'A line with multiple spaces'
outputLine = LineParser().capitalize(outputLine);
// 'A Line With Multiple Spaces'
outputLine = LineParser().formatSomethingElse(outputLine);
// Some more formatting, then do further processing with outputLine
If I run the sequence using callbacks, it is going to become an ugly set of nested callbacks really quickly when I have, say, 10 simple processing functions.
If I add methods chaining, the idea of prototype methods looks against functional style too, because functions in the chain will depend on previous state, not only on the input they get.
What should I do to make it look nicer in a functional style?
Update: After deeper research I found topic named Function Composition. It seems to be a proper solution to the problem and is one of the basic things from the functional world.
Here is the function I use to compose multiple functions into one:
var compose = function () {
var funcs = arguments;
return function () {
var args = arguments;
for (var i = funcs.length; i-- > 0;) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
Then I do a composition:
var composedFunction = compose(func1, func2, ..., funcn)
Which run from the right to left and all works just fine.
You lineparser seems to have methods like formatSpaces, capitalize and formatSomethingElse. The easiest thing you could do is to make all those methods to return this, so that you can chain those methods like so:
var outputline = LineParser.formatSpaces(inputLine).capitalize().formatSomethingElse()
Though by the looks of it, all of the methods require some string as a parameter, so you might have to make some implementation changes such as saving the string in a private variable if given and pullin it from the variable if no parameters are given.
Remark about your Edit. The function compose is very functional in the principle but not in its implementation. Indeed, the function mutates some variables (e.g., i and args) and is therefore not fully functional.
To avoid using these mutating variables, you could possibly define compose recursively. Another solution ould be to rely on third-party functional library, such as underscore-js for example (http://underscorejs.org/), which already defines a composition function.
Additional (obvious) remark: to make your code functional with compose, the functions func1, func2,... that are composed, should not mutate their arguments.
If you want asynchronous programming but you don't like nested callbacks, have you considered the async lib ?
You could have something like this :
var LineParser = require('../modules/LineParser');
var inputLine = 'A line with multiple spaces';
async.waterfall([
function(callback) {
var result = LineParser().formatSpaces(inputLine);
callback(null, result);
},
function(arg1, callback) {
var result = LineParser().capitalize(arg1);
callback(null, result);
},
function(arg1, callback) {
var result = LineParser().formatSomethingElse(arg1);
callback(null, result);
}
], function (err, result) {
// retrieve the final string
});
which can be turned into something useful if you modify your LineParser methods into asynchronous methods (otherwise it will only make your 3 lines heavier)
Functional style, that is, pure functional style that we see in Lisp etc. looks like this:
var outputline = formatSomethingElse(capitalize(formatSpaces(inputline)));
Often, for readability it would be formatted as:
var outputline = formatSomethingElse(
capitalize(
formatSpaces(inputline)
)
);
Any other form is not functional style. Functional style are a bit like Reverse Polish Notation in that the stated operation should be read in reverse. Indeed, RPN is itself a functional programming syntax (as embodied by Forth).
There is a style that has a similar look and feel to the functional style: method chaining:
var outputline = LineParser(inputline)
.formatSpaces()
.capitalize()
.formatSomethingElse()
.toString();
Unlike functional style, method chaining is read in order.
While the most famous chaining library, jQuery, mutates the state of the object it's not really necessary to do that. Take for example the following simple implementation of LineParser:
function LineParser (text) {
return {
text: text,
toString: function () {return this.text},
capitalize: function () {
// return a new object instead of "this"
return {
text : _capitalize(this.text),
toString : this.toString
}
}
}
}
how can i do prototypal inheritance in javasciript. usually i do by this
and
derivedFn.prototype = object.create(clsParent.prototype)
but today i got we can also do this the result is same so what is the differce
derivedFn.prototype = clsParent.prototype
For example
function clsParent() {
this.myName = "faizan"
this.getMyName = function() {}
}
clsParent.prototype.aProp = "property in prototype"
function clsChild() {
this.Fname = "abr"
}
clsChild.prototype = clsParent.prototype; //what is the difference
//Object.create(clsParent.prototype);
// what is the difference if i do inheritance by this
var myObj = new clsChild();
console.log(myObj.myName);
console.log(myObj.aProp);
code is given please clarify me the difference of these two ways inheritance
When you say
clsChild.prototype = clsParent.prototype;
You are making both the clsChild and clsParent's prototypes the same. So, if you make changes to clsChild.prototype, the changes will be visible in any objects created with new clsParent() as well.
Try,
clsChild.prototype.a = 1000;
console.log(new clsParent().a);
// 1000
But when you do Object.create(clsParent.prototype), it will create a brand new object which extends from clsParent.prototype. So, making changes to clsChild.prototype will not affect clsParent.prototype.
Suggestion:
It is usually a bad idea to store a property in the prototype, since it will be shared by all the instances. You should do this only if your usecase demands it.
clsParent.prototype.aProp = "property in prototype"; // Don't do this
In addition to what thefourtheye said. I think it's mostly a matter of clarity. It's easier to think about objects when each class has an object to represent it. Additionally it's probably the most common way of implementing inheritance, which also makes it easier to understand.
Also there are no technical reasons not to store primitives values in a prototype. But it becomes confusing when you define integer properties in one part of the file, and array properties in another.
Is there any kind of persistence framework for JavaScript and/or the Google v8 engine?
I want to store (serialize) a whole graph of objects (including, e.g., functions) and re-load it later. JSON is not sufficient, since it does not permit functions to be stored and permits only a tree-like structure (i.e. no two objects referencing the same object).
I need to be able to do that generically (i.e. without knowing the JavaScript code at the time at which I write my program embedding v8), since I want the user of my program to be able to customize it with JavaScript, but I need to store the state of my program (including the state of the customization) and re-load it later. Hence I need to store the state of the JavaScript engine.
Edit:
Example:
Suppose we have the following code:
var obj = { a: 4, b: function (x) { return x + this.a; } }
// ...
if ( ... ) { obj.a = 5; }
// ...
if ( ... ) { var c = 1; obj.b = function (x) { return x + this.a + c; } }
// ...
// now I want to serialize obj
Then is it (without any meta-information about the logic of the program) possible to serialize obj and later deserialize it such that obj.b (2) delivers the same result after deserialization as it did before serialization?
Second Edit: Note the closure.
Unfortunately, what you're trying to do is not currently possible in Javascript. The reason is that closures are not just objects, they're objects bound to an execution context.
Getting past the "this can't be done in javascript" issue and moving into the "what if wrote a patch for V8 to allow this" phase of the answer, this is conceptually difficult. Essentially, for every closure you'd serialize, you would have to serialize the Context object that the closure exists in. It'd be nice to be able to just serialize the HandleScope, but the nature of closures is that you can't reach inside them.
Okay, so let's say you've written a function that can serialize the Context that the closure exists in, and you can even deserialize it. What do you do with it?
The answer to that is 'not much'. Javascript can only be executed in a single context at a time. The closure that you've deserialized doesn't exists in the context that you're trying to pull it back into. You can't really pass data between contexts, and if your function has data bound to free variables, do you use the ones that exist in the deserializer-invoking context, or do you overwrite it with the deserialized context? Conceptually, this is a nightmare.
Ecmascript Harmony had considered giving us nearly-first-class continuations, but it's been pushed form the discussion which I rant about here, but this isn't going to happen any time soon.
HTML5 local storage allows persistence at client level through javascript.
I'm not sure if it will fit your needings, as to being able to store a function you'll need to somewhat give it some markup that allows you to deserialize it when retrieving it from storage (or maybe just store it as plain text and try to eval it on retrieval)
http://diveintohtml5.info/storage.html
I don't think persisting functions is a good practice. I can suggest you the below approach. Turn your JSON data to lets say some class like "MyData". You can find two functions fromJSON, toJSON which will do the magic you want.
var MyData = function(props){
this.temp = "a";
this.getTemp = function(){
return this.temp;
}
this.fromJSON = function(props){
if(props){
this.temp = props.temp;
}
}
this.toJSON = function(){
var props = {};
props.temp = this.temp;
return props;
}
this.fromJSON(props);
}
var obj = new MyData({"temp" : "b"});
var state = obj.toJSON();
// persist state about the object as JSON string
LOCALSTORAGE.put(state); // You can write some HTML5 local storage stuff to persist
var persistedState = LOCALSTORAGE.get(); // You can use the above HTML5 local storage stuff to read the persisted stuff
var newBornObj = new MyData(persistedState);
I have a function that takes a string object name and I need the function to create an new instance of a object that has the same name as the value of the string
For example,
function Foo(){}
function create(name){
return new name();
}
create('Foo'); //should be equivalent to new Foo();
While I know this would be possible via eval, it would be good to try and avoid using it. I am also interested if anyone has an alternative ideas to the problem (below)
I have a database and a set of (using classical OO methodology) classes, roughly one for each table that define common operations on that table. (Very similar to Zend_Db for those who use PHP). As everything is asynchronous doing tasks based on the result of the last one can lead to very indented code
var table1 = new Table1Db();
table1.doFoo({
success:function(){
var table2 = new Table2Db();
table2.doBar({
notFound:function(){
doStuff();
}
});
}
});
The obvious solution is to create helper methods that abstracts the asynchronous nature of the code.
Db.using(db) //the database object
.require('Table1', 'doFoo', 'success') //table name, function, excpected callback
.require('Table2', 'doBar', 'notFound')
.then(doStuff);
Which simplifies things. However the problem is that I need to be able to create the table classes, the names of which can be inferred from the first augment passed to require which leads me to the problem above...
Why not simply pass the constructor function into the require method? That way you sidestep the whole issue of converting from name to function. Your example would then look like:
Db.using(db) //the database object
.require(Table1Db, 'doFoo', 'success') //table constructor, function name, expected callback
.require(Table2Db, 'doBar', 'notFound')
.then(doStuff);
However, if you really want to use a string...
Why are you deadset on avoiding using eval? It is a tool in the language and every tool has its purpose (just as every tool can be misused). If you're concerned about allowing arbitrary execution, a simple regular expression test should render your usage safe.
If you're dead-set on avoiding eval and if all of your constructor functions are created in the default global scope (i.e. the window object), this would work:
function create(name) {
return new window[name]();
}
If you want to get fancy and support namespace objects (i.e. create('MyCompany.MyLibrary.MyObject'), you could do something like this:
function create(name) {
var current,
parts,
constructorName;
parts = name.split('.');
constructorName = parts[parts.length - 1];
current = window;
for (var i = 0; i < parts.length - 1; i++) {
current = current[parts[i]];
}
return new current[constructorName]();
}
You were at the gate of completeness. While Annabelle's solution let's you to do what's you've just wanted in the way you wanted (passing strings), let me offer you an alternative. (passing function references)
function Foo(){}
function create(name){
return new name();
}
create(Foo); // IS equivalent to new Foo();
And voila, it works :) I told you. You were at the doorsteps of the solution.
What happened is that you've try to do this
new 'Foo'()
Which doesn't makes much sense, does it? But now you pass the function by reference so the line return new name(); will be transformed into return new Foo(); just how you would expect.
And now the doors are opened to abstract the asynchronousness of your application. Have fun!
Appendix: Functions are first-class objects, which means that they can be stored by reference, passed as an argument by reference or returned by another function as values.