How to Bring All of an Objects Properties ForeFront? - javascript

Begin:
The Math object in JavaScript can prove to be extremely useful. In a page using the Math object repeatedly, I would rather not continuously use. I would prefer to use these functions at top-level. I will provide an example on how this is possible:
The With Keyword (Bad Way):
Let me state the following: This is absolutely terrible, never use it.
with(Math) {
let q = min(10,211);
let r = max(2,8);
let e = random();
let p = floor(e*r)
console.log(q*r/e)
}
Bringing an Object to Front By Defining It As Such (Good Way):
I enjoy using this way much more than the way above.
let {min,max,random,floor} = Math;
let q = min(10,211);
let r = max(2,8);
let e = random();
let p = floor(e*r);
console.log(q*r/e);
Continuation:
I am asking if anyone knows of a way to accomplish what the with keyword does without with because I find with terrible. I am curious to know if it is possible to get all of the words of Math and store it into an Object that is defined as Math. I understand that this may be confusing. Thank you for reading.

For ordinary objects (instances of the Object class) you could use Object.assign to add their properties to the window object. But for Math and the other base objects their properties seem not to be enumerable. Instead, following this answer you can use Object.getOwnPropertyNames to find all the properties of Math and attach them to the window object.
for (let prop of Object.getOwnPropertyNames(Math)) {
window[prop] = Math[prop];
}
console.log(PI); // 3.14...
I would suggest this is not a great practice as it is not very transparent about what names are being added to the global namespace.

Related

How do i dynamically reference an object and its object and property in JS

I'm passing a property options_r into a function but i need to reference to its properties dynamically...
to illustrate in a simple way, here's a function that takes in a parameter.
options_r = {}
function blah(myData,options_r) {
output_data = myData[options_r.target]; //
alert(output_data)
}
THIS WORKS
myData.joe = 'male';
myData.anne = 'female';
let options_r.target = 'joe';
blah(myData, options_r);
THIS DOESNT
myData.dataset.joe = 'male';
myData.dataset.anne = 'female';
let options_r.target = 'dataset.joe';
blah(myData, options_r);
...and yes sometimes in need to reference an object within an object this way.
Any ideas?
Thanks!
What you are trying to acomplish is not a native feature of JavaScript.
Some common extension libraries do that, for example _.get function of lodash. Where in your case if you use this you will be able to do
_.get(myData, options_r.target);
Otherwise, you will have to code something that parse your path and does smart object traversal yourself.
The last option would be to use a solution based around eval but I really wouldn't advise going that route.

how to name a method in functional programming JavaScript

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.

Memory handling vs. performance

I'm building a WebGL game and I've come so far that I've started to investigate performance bottlenecks. I can see there are a lot of small dips in FPS when there are GC going on. Hence, I created a small memory pool handler. I still see a lot of GC after I've started to use it and I might suspect that I've got something wrong.
My memory pool code looks like this:
function Memory(Class) {
this.Class = Class;
this.pool = [];
Memory.prototype.size = function() {
return this.pool.length;
};
Memory.prototype.allocate = function() {
if (this.pool.length === 0) {
var x = new this.Class();
if(typeof(x) == "object") {
x.size = 0;
x.push = function(v) { this[this.size++] = v; };
x.pop = function() { return this[--this.size]; };
}
return x;
} else {
return this.pool.pop();
}
};
Memory.prototype.free = function(object) {
if(typeof(object) == "object") {
object.size = 0;
}
this.pool.push(object);
};
Memory.prototype.gc = function() {
this.pool = [];
};
}
I then use this class like this:
game.mInt = new Memory(Number);
game.mArray = new Memory(Array); // this will have a new push() and size property.
// Allocate an number
var x = game.mInt.allocate();
<do something with it, for loop etc>
// Free variable and push into mInt pool to be reused.
game.mInt.free(x);
My memory handling for an array is based on using myArray.size instead of length, which keeps track of the actual current array size in an overdimensioned array (that has been reused).
So to my actual question:
Using this approach to avoid GC and keep memory during play-time. Will my variables I declare with "var" inside functions still be GC even though they are returned as new Class() from my Memory function?
Example:
var x = game.mInt.allocate();
for(x = 0; x < 100; x++) {
...
}
x = game.mInt.free(x);
Will this still cause memory garbage collection of the "var" due to some memcopy behind the scenes? (which would make my memory handler useless)
Is my approach good/meaningful in my case with a game that I'm trying to get high FPS in?
So you let JS instantiate a new Object
var x = new this.Class();
then add anonymous methods to this object and therefore make it a one of a kind
x.push = function...
x.pop = function...
so that now every place you're using this object is harder to optimize by the JS engine, because they have now distinct interfaces/hidden classes (equal ain't identical)
Additionally, every place you use these objects, will have to implement additional typecasts, to convert the Number Object back into a primitive, and typecasts ain't for free either. Like, in every iteration of a loop? maybe even multiple times?
And all this overhead just to store a 64bit float?
game.mInt = new Memory(Number);
And since you cannot change the internal State and therefore the value of a Number object, these values are basically static, like their primitive counterpart.
TL;DR:
Don't pool native types, especially not primitives. These days, JS is pretty good at optimizing the code if it doesn't have to deal with surprizes. Surprizes like distinct objects with distinct interfaces that first have to be cast to a primitive value, before they can be used.
Array resizing ain't for free either. Although JS optimizes this and usually pre-allocates more memory than the Array may need, you may still hit that limit, and therefore enforce the engine to allocate new memory, move all the values to that new memory and free the old one.
I usually use Linked lists for pools.
Don't try to pool everything. Think about wich objects can really be reused, and wich you are bending to fit them into this narrative of "reusability".
I'd say: If you have to do as little as adding a single new property to an object (after it has been constructed), and therefore you'd need to delete this property for clean up, this object should not be pooled.
Hidden Classes: When talking about optimizations in JS you should know this topic at least at a very basic level
summary:
don't add new properties after an object has been constructed.
and to extend this first point, no deletes!
the order in wich you add properties matters
changing the value of a property (even its type) doesn't matter! Except when we talk about properties that contain functions (aka. methods). The optimizer may be a bit picky here, when we're talking about functions attached to objects, so avoid it.
And last but not least: Distinct between optimized and "dictionary" objects. First in your concepts, then in your code.
There's no benefit in trying to fit everything into a pattern with static interfaces (this is JS, not Java). But static types make the life easier for the optimizer. So compose the two.

difference b\w clsParent.prototype and object.create(clsParent.prototype)

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 it okay to use with()?

Once, I saw an example like this:
var a, x, y;
var r = 10;
with (Math) {
a = PI * r * r;
x = r * cos(PI);
y = r * sin(PI / 2);
}
And it looks very convenience, because that way I don't have to type all the Math.s.
But when I take a look at the MDN, it says:
Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable.
So is it okay to use with()? In HTML5?
The MDN you linked says Using with is not recommended...
with is an excellent way of making spaghetti code for lunch.
You might like it, but the guy that will need to debug it will curse you.
javascript has some very weird operators, like the comma operator(,).
Can you understand what the following code does?
var a = "a";
var b = "b";
a = [b][b = a,0];
Well it swaps a and b... You don't understand , so as the guy that will need maintain your with code. Don't use hacks, hacks are cool in charades games, not in real code.
When is the comma operator useful?
The comma swap Fiddle
It is okay to use any feature of JavaScript, so long as you understand it.
For example, using with you can access existing properties of an object, but you cannot create new ones.
Observe:
var obj = {a:1,b:2};
with(obj) {
a = 3;
c = 5;
}
// obj is now {a:3,b:2}, and there is a global variable c with the value 5
It can be useful for shortening code, such as:
with(elem.parentNode.children[elem.parentNode.children.length-3].lastChild.style) {
backgroundColor = "red";
color = "white";
fontWeight = "bold";
}
Because the properties of the style object already exist.
I hope this explanation is clear enough.
In his excellent book "Javascript: The Good Parts", Douglas Crockford lists the "with Statement" in Appendix B: The Bad Parts.
He says "Unfortunately its results can sometimes be unpredictable, so it should be avoided".
He goes on to give an example, where an assignment inside the with will operate on different variables depending on whether the object is defined or not.
See With statement considered harmful (but less detailed than the explanation in the book).

Categories