Creating new Objects inside for loop in Nodejs and assigning it to variable with let? - node.js

for() {
let obj1 = new Object();
}
Is this any different, with regard to performance, from
let obj1;
for() {
obj1 = new Object();
}

Yes. It's different, because when using 'let' that variable will only exists inside the for loop and at every iteration you will be creating a new variable.
When you declare the let obj outside the for, it can be used inside and outside the loop.
Check this for more info https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
Hope it helped :)

Related

Rust: How to initialise a value in one conditional branch for use in another?

I want to do something similar to the following pseudo Rust code:
let mut var;
for i in iter {
if condition {
var = some_obj;
}
else {
var.some_method();
}
}
The obvious problem is that var.some_method(); may run before var has been initialized in the true branch, and so this code won't compile.
I have a use case however where I know for sure that the false branch won't execute until the true branch has at least once. I'd like to be able to define var based on the results computed in the true branch, and then use it in the false branch on future loop iterations.
My only idea is to initialize var with a dummy variable outside of the loop, but this seems quite hacky. Is there a clean way to achieve what I want here?
You can make var have type Option<T> and since you are sure var has been set when the else block is executed you can call var.unwrap().some_method. When you are going to set var it should be var = Some(some_obj);.
There also might be some way to do this using MaybeUninnit and/or using unsafe code, but you should only do that if you're (really) comfortable with rust

Maintain Composition Root when creating components in a Parallel.Foreach loop (threading)

I'm trying to learn the correct way inside a Parallel ForEach loop to not reference composition root yet create a thread component based on the component referenced in the composition root.
This is the composition root code:
var builder = new ContainerBuilder();
builder.RegisterType<OperationFiscalCalendarSql>().As<IOperationCloser>().InstancePerDependency();
builder.RegisterType<SQLMessagePoller>().As<IMessagePoller>().SingleInstance();
...
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
...
}
and this is the code that is referenced in the poller object that has the foreach loop:
Parallel.ForEach(messageHeaders, new ParallelOptions { MaxDegreeOfParallelism = _maxDegreeOfParallelism }, messageHeader => {
...
var sapCloser = new OperationFiscalCalendarSql(closeObj, repostiory);
...
});
Note I want an instance of IOperationCloser instead of hardcoding a 'new'ed up OperationFiscalCalendarSql object.
I understand constructor injection I just don't know how to inject an IOperationCloser when it is in any kind of loop.
You can inject a factory in your Poller object with Func<IOperationCloser> and then get a new instance in the ForEach loop.
In your case it may be even better to create your own ILifetimeScope. You can do this by injecting ILieetimeScope in Poller and then call BeginLifetimeScope and Resolve in the loop.
Parallel.ForEach(messageHeaders, ..., m => {
using(ILifetimeScope childScope = scope.BeginLifetimeScope()){
var param1 = new TypedParameter(m);
var closer = childScope.Resolve<IOperationCloser>(param1);
});
});

How to hold a reference to broadcast variable

Where, in a scala application, is the best place to store a Spark broadcast variable, so that it can be referenced elsewhere in the app?
val broadcast:Broadcast = ...
It does not appear to be possible to save it in an Object, because:
an object cannot have an uninitialized variable, so it cannot be
passed a reference to the broadcast variable by calling a method on the object to set the reference.
an Object cannot setup the broadcast variable
itself, as an object has no constructor into which to pass a
reference to the SparkContext.
Thanks
Using a var rather than a val is likely the solution.
The following is one approach. In the example, the broadcast variable is being used to hold a cache.
Object Cache {
private var cache:Broadcast;
// This method must be called by client to initialize the cache
def init(sc:SparkContext) = {
cache = sc.broadcast(loadCache)
}
def getCache() = {
// check that variable is initialized
if cache!=null {
Some(cache)
}
else
{
None
}
}
private def loadCache():List[String] = {
// load data from DB
}
}

Does assigning module.exports to a separate object waste memory

There are two basic ways that I see Node modules being written. The first setting each function or variable you want to export to its own property on module.exports:
module.exports.foo = function () {
...
}
And the second is creating a new object that has the properties you want to export, and assigning module.exports to that at the end of the file:
var FooObject = {
foo: function () {
...
}
};
...
module.exports = FooObject;
A third thing that I sometimes see is setting module.exports to an object which has all the properties you want to export, but for the purposes of this discussion, that's equivalent to the first method I mentioned:
module.exports = {
foo: function () {
...
}
}
Are we wasting memory by doing it the second way (creating an object and assigning module.exports to that)? I always thought that since all assignment is a reference, a new object should be created when you do module.exports = {...} so these two would be equivalent. Is that not the case?
The last two examples are equivalent. The only difference is that the second one is setting the object by name and the third is setting it by the object literal.

How to implement inheritance in Node.JS

How do we use 'inheritance' in Node.JS? I heard that prototype is similar to interfaces in java. But I have no idea how to use it!
Although there are various ways of performing inheritance and OO in javascript, in Node.js you would typically use the built in util.inherits function to create a constructor which inherits from another.
See http://book.mixu.net/ch6.html for a good discussion on this subject.
for example:
var util = require("util");
var events = require("events");
function MyOwnClass() {
// ... your code.
}
util.inherits(MyOwnClass, events.EventEmitter);
Creating an object constructor in pure JS:
They're just functions like any other JS function but invoked with the new keyword.
function Constructor(){ //constructors are typically capitalized
this.public = function(){ alert(private); }
var private = "Untouchable outside of this func scope.";
}
Constructor.static = function(){ alert('Callable as "Constructor.static()"'); }
var instance = new Constructor();
Inheritance:
function SubConstructor(){
this.anotherMethod(){ alert('nothing special'); }
}
function SubConstructor.prototype = new Constructor();
var instance = new SubConstructor();
instance.public(); //alerts that private string
The key difference is that prototypal inheritance comes from objects, rather than the things that build them.
One disadvantage is that there's no pretty way to write something that makes inheritance of instance vars like private possible.
The whopping gigantor mega-advantage, however, is that we can mess with the prototype without impacting the super constructor, changing a method or property for every object even after they've been built. This is rarely done in practice in higher-level code since it would make for an awfully confusing API but it can be handy for under-the-hood type stuff where you might want to share a changing value across a set of instances without just making it global.
The reason we get this post-instantiated behavior is because JS inheritance actually operates on a lookup process where any method call runs up the chain of instances and their constructor prototype properties until it finds the method called or quits. This can actually get slow if you go absolutely insane with cascading inheritance (which is widely regarded as an anti-pattern anyway).
I don't actually hit prototype specifically for inheritacne a lot myself, instead preferring to build up objects via a more composited approach but it's very handy when you need it and offers a lot of less obvious utility. For instance when you have an object that would be useful to you if only one property were different, but you don't want to touch the original.
var originInstance = {
originValue:'only on origin',
theOneProperty:'that would make this old object useful if it were different'
}
function Pseudoclone(){
this.theOneProperty = "which is now this value";
}
Pseudoclone.prototype = originInstance;
var newInstance = new Psuedoclone();
//accesses originInstance.originValue but its own theOneProperty
There are more modern convenience methods like Object.create but only function constructors give you the option to encapsulate private/instance vars so I tend to favor them since 9 times out of 10 anything not requiring encapsulation will just be an object literal anyway.
Overriding and Call Object Order:
( function Constructor(){
var private = "public referencing private";
this.myMethod = function(){ alert(private); }
} ).prototype = { myMethod:function(){ alert('prototype'); };
var instance = new Constructor();
instance.myMethod = function(){ alert(private); }
instance.myMethod();//"undefined"
Note: the parens around the constructor allow it to be defined and evaluated in one spot so I could treat it like an object on the same line.
myMethod is alerting "undefined" because an externally overwritten method is defined outside of the constructor's closure which is what effective makes internal vars private-like. So you can replace the method but you won't have access to what it did.
Now let's do some commenting.
( function Constructor(){
var private = "public referencing private";
this.myMethod = function(){ alert(private); }
} ).prototype = { myMethod:function(){ alert('prototype'); };
var instance = new Constructor();
//instance.myMethod = function(){ alert(private); }
instance.myMethod();//"public referencing private"
and...
( function Constructor(){
var private = "public referencing private";
//this.myMethod = function(){ alert(private); }
} ).prototype = { myMethod:function(){ alert('prototype'); };
var instance = new Constructor();
//instance.myMethod = function(){ alert(private); }
instance.myMethod();//"prototype"
Note that prototype methods also don't have access to that internal private var for the same reason. It's all about whether something was defined in the constructor itself. Note that params passed to the constructor will also effectively be private instance vars which can be handy for doing things like overriding a set of default options.
Couple More Details
It's actually not necessary to use parens when invoking with new unless you have required parameters but I tend to leave them in out of habit (it works to think of them as functions that fire and then leave an object representing the scope of that firing behind) and figured it would be less alien to a Java dev than new Constructor;
Also, with any constructor that requires params, I like to add default values internally with something like:
var param = param || '';
That way you can pass the constructor into convenience methods like Node's util.inherit without undefined values breaking things for you.
Params are also effectively private persistent instance vars just like any var defined in a constructor.
Oh and object literals (objects defined with { key:'value' }) are probably best thought of as roughly equivalent to this:
var instance = new Object();
instance.key = 'value';
With a little help from Coffeescript, we can achieve it much easier.
For e.g.: to extend a class:
class Animal
constructor: (#name) ->
alive: ->
false
class Parrot extends Animal
constructor: ->
super("Parrot")
dead: ->
not #alive()
Static property:
class Animal
#find: (name) ->
Animal.find("Parrot")
Instance property:
class Animal
price: 5
sell: (customer) ->
animal = new Animal
animal.sell(new Customer)
I just take the sample code Classes in CoffeeScript. You can learn more about CoffeeScript at its official site: http://coffeescript.org/

Resources