Is it possible to add an element after a set height interval? - javascript

I need to add an element like <div> end </div> every 100px. Is there any possible solution using Javascript, jQuery or php?
jsfiddle.net/vk4a7pwo/24 This is where my code is. I need the content of class .message-append put inside the .subpage class.
<div class="page">
<div class="subpage"></div>
</div>
<div class="page">
<div class="subpage"></div>
</div>
<div class="message-append"><p><strong>This article examines four new ES6 collections and the benefits they provide.</strong></p><p>Most major programming languages have several types of data collections. Python has lists, tuples, and dictionaries. Java has lists, sets, maps, queues. Ruby has hashes and arrays. JavaScript, up until now, had only arrays. Objects and arrays were the workhorses of JavaScript. ES6 introduces four new data structures that will add power and expressiveness to the language: </p><h2>Searching for the JavaScript HashMap</h2><p>HashMaps, dictionaries, and hashes are several ways that various programming languages store key/value pairs, and these data structures are optimized for fast retrieval.</p><p>In ES5, JavaScript objects — which are just arbitrary collections of properties with keys and values — can simulate hashes, but there are .</p><h3>Downside #1: Keys must be strings in ES5</h3><p>JavaScript object property keys must be strings, which limits their ability to serve as a collection of key/value pairs of varying data types. You can, of course, coerce/stringify other data types into strings, but this adds extra work.</p><h3>Downside #2: Objects are not inherently iterable</h3><p>Objects weren’t designed to be used as collections, and as a result there’s no efficient way to determine how many properties an object has. . When you loop over an object’s properties, you also get its prototype properties. You could add the property to all objects, but not all objects are meant to be used as collections. You could use the method, but this is just a workaround. When you loop over an object’s properties, the properties won’t necessarily be retrieved in the same order they were inserted.</p><h3>Downside #3: Challenges with built-in method collisions</h3><p>Objects have built-in methods like </p><p>ES6 includes new collection data types, so there’s no longer a need to use objects and live with their drawbacks.</p><h2>Using ES6 Map Collections</h2><p>is the first data structure/collection we’ll examine. Maps are collections of keys and values of any type. It’s easy to create new Maps, add/remove values, loop over keys/values and efficiently determine their size. Here are the crucial methods:</p></div>

Related

Sharing array of nested objects between workers

I have an array of objects which contains more objects as values. I'm working with Web Workers and I need to use this exact array of objects (or another object) in worker file. Problem is I couldn't find any solution to forward this array or object from main file to worker.
I cannot use Shared Array Buffer because it needs Typed Arrays (or I couldn't find any solution). And stringifying doesn't work because after parsing the reserve array that keeping my objects which I am using to compare can not recognize object.
Two threads cannot share an array of objects. While it's possible to transfer arrays with some objects in them between threads (where the source thread loses access to those objects, until or unless the target thread sends them back), you can only do that with transferrable objects, and plain objects are not transferrable.
You'll need to use some kind of serialization turning the objects into strings or transferable objects, and then handle deserializing them.
And stringifying doesn't work because after parsing the reserve array that keeping my objects which I am using to compare can not recognize object.
You'll need to give them unique IDs that allow you to relate the serialized version back to the original.

How does mongo retain order of an object when defining an index?

From the mongodb docs
Docs link
But in javascript you can't depend on the order of keys in an object 😱. So how does mongo reliably preserve the order of item and stock in the above example of a compound index?
No idea what the folks at MongoDB were smoking when they defined this API. As you have rightly pointed out, the JavaScript object only represents the unordered collection of key-value pairs both by design and spirit. For ordered collection, one could use array of objects.
The recent versions of JavaScript specifications encourage preserving the creation order of keys in the object for Object.keys and such methods. As others pointed out in the comments, relying on creation order of properties for the Object parameter for an API is plain stupid. It becomes even muddier if the object is cloned, the cloning library maintains the order or not. But probably it works since recent implementations now a days honors creation order and they pass the constant object inline.

Hashtable vs objects In javascript

I’m new to data structure and I’m learning it in Javascript.
My Question is:
Why do we need hash tables when we 've objects in javascript?
Can anybody give me a situation where hash tables will be more useful than objects?
"Hashtable" is called different things in different languages. Java has Hashtable and HashMap, Ruby has Hash, Python has dict... in JavaScript, it's called Map.
Objects' keys are limited to strings; Map keys can be anything.
Objects support inheritance; a Map only contains what is specifically put into it.
Think you means Map instead of HashTable. IMHO Map may be more useful and perform better if you need one of that:
keep order of insertions of key/value pairs;
frequent additional and removal;
key which not String/Symbol.
I think you can obtain more information at MDN
The MDN docs on this are quite helpful: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared
Most notably, using a map gives you the advantage of using anything as a key, maps retain order, and may perform better when constantly adding and removing values.

Is it possible to disable Firebase's auto-conversion to native arrays?

In the Firebase documentation, it says:
Firebase stores all data as Objects, even Arrays are stored as objects with numerical keys.
As a convenience, the Firebase Web API automatically converts Array-like Objects into Arrays
for use JavaScript.
This "convenience" is a royal pain, in my opinion. Is there any way to disable the automatic conversion, while still using array-like objects with numerical keys? I am using the arrayjs library, and would like to maintain those array-like objects throughout the application.
It also says in the docs: "It's not currently possible to change or prevent this behavior." So no, you can't disable it.
You can work around it as follows:
add any non-numeric key to the path (e.g. "ignoreme": true), which will prevent any keys from being treated as numeric
prefix the item keys with a string (e.g. "rec1", "rec2"...)
make the numbers non-consecutive
But in reality, sequential numeric ids in distributed real-time data are ill advised and should be avoided for most cases. They cause nothing but heartache.

Object vs Arrays in Javascript is as Python's Dictionaries vs Lists?

I know in python I can use lists in order to make fast sortings and dictionaries in order to search things faster (because immutable objects can be hashed). Is that the same for javascript too? I haven't seen anything about the performance of datatypes in javascript after much search.
Yes. "Object vs Arrays in Javascript is as Python's Dictionaries vs Lists".
Performance pros and cons are also the same. With lists being more efficient if numeric indexes are appropriate to the task and dictionaries being more efficient for long lists that must be accessed by a string.
var dict = {};
dict['apple'] = "a sweet edible fruit";
dict['boy'] = "a young male human";
var list = [];
list.push("apples");
list.push("oranges");
list.push("pears");
I have been looking for some bibliography and other sources that could answer this question. I Know that this isn't the best answer, but let me try an answer that involve some concepts that lend us to discuss this topic.
Javascript and inheritance
Although the it could suggest that arrays and objects in javascript are like lists and dictionaries, they are different because each language are written in different ways, with different underlying philosophies, concepts and purposes.
In the case of Javascript, it seems that both Arryas and Objects are more like hash tables. Contrary to the intuition, Arrays are just an other type of built in object of javascript. In fact, as they say in the ECMAScript Specification 6.1.7
The Object Type
An Object is logically a collection of properties. Each property is
either a data property, or an accessor property:
A data property associates a key value with an ECMAScript language
value and a set of Boolean attributes. An accessor property associates
a key value with one or two accessor functions, and a set of Boolean
attributes. The accessor functions are used to store or retrieve an
ECMAScript language value that is associated with the property.
Properties are identified using key values. A property key value is
either an ECMAScript String value or a Symbol value. All String and
Symbol values, including the empty string, are valid as property keys.
A property name is a property key that is a String value.
An integer index is a String-valued property key that is a canonical
numeric String (see 7.1.16) and whose numeric value is either +0 or a
positive integer ≤ 253 - 1. An array index is an integer index whose
numeric value i is in the range +0 ≤ i < 232 - 1.
Property keys are used to access properties and their values. There
are two kinds of access for properties: get and set, corresponding to
value retrieval and assignment, respectively. The properties
accessible via get and set access includes both own properties that
are a direct part of an object and inherited properties which are
provided by another associated object via a property inheritance
relationship. Inherited properties may be either own or inherited
properties of the associated object. Each own property of an object
must each have a key value that is distinct from the key values of the
other own properties of that object.
And,about the arrays, it specifies:
22.1Array Objects
Array objects are exotic objects that give special treatment to a certain class of property names.
Following the logic above, and as it says in the specification, the language was thinked in such way that all types in javascript extends a global object, and then new methods and properties are added to have differents behaivors.
Memory Management
There are a gap between the language specifications and how they must be implemented in an actual runtime enviroment. Altought each implementation has its own logics, it seems that most of them has similarities.
As This Article Explains:
Most JavaScript interpreters use dictionary-like structures (hash
function based) to store the location of object property values in the
memory. This structure makes retrieving the value of a property in
JavaScript more computationally expensive than it would be in a
non-dynamic programming language like Java or C#. In Java, all of the
object properties are determined by a fixed object layout before
compilation and cannot be dynamically added or removed at runtime
(well, C# has the dynamic type which is another topic). As a result,
the values of properties (or pointers to those properties) can be
stored as a continuous buffer in the memory with a fixed-offset
between each. The length of an offset can easily be determined based
on the property type, whereas this is not possible in JavaScript where
a property type can change during runtime.
As this make javascript kind of ineffitient, the engineers had to came with some clever workarounds in order to solve this problem. Following this other article:
If you access a property, e.g. object.y, the JavaScript engine looks
in the JSObject for the key 'y', then loads the corresponding property
attributes, and finally returns the [[Value]].
But where are these property attributes stored in memory? Should we
store them as part of the JSObject? If we assume that we’ll be seeing
more objects with this shape later, then it’s wasteful to store the
full dictionary containing the property names and attributes on the
JSObject itself, as the property names are repeated for all objects
with the same shape. That’s a lot of duplication and unnecessarily
memory usage. As an optimization, engines store the Shape of the
object separately.
This Shape contains all the property names and the attributes, except
for their [[Value]]s. Instead the Shape contains the offset of the
values inside of the JSObject, so that the JavaScript engine knows
where to find the values. Every JSObject with this same shape points
to exactly this Shape instance. Now every JSObject only has to store
the values that are unique to this object.
The benefit becomes clear when we have multiple objects. No matter how
many objects there are, as long as they have the same shape, we only
have to store the shape and property information once!
All JavaScript engines use shapes as an optimization, but they don’t
all call them shapes:
Academic papers call them Hidden Classes (confusing w.r.t. JavaScript classes)
V8 calls them Maps (confusing w.r.t. JavaScript Maps)
Chakra calls them Types (confusing w.r.t. JavaScript’s dynamic types and typeof)
JavaScriptCore calls them Structures
*SpiderMonkey calls them Shapes
Python
Arrays
Python uses a different aproach for the implementation of lists, it seems that lists are more like some dynamics arrays than an actual array that you could find in C, But they are sill are focussed on saving spaces of time and complexity in a runtime. As this FAQ cited form the PyDocs says:
Python’s list objects are really variable-length arrays, not
Lisp-style linked lists. The implementation uses a contiguous array of
references to other objects, and keeps a pointer to this array and the
array’s length in a list head structure.
This makes indexing a list (L[i]) an operation whose cost is
independent of the size of the list or the value of the index.
When items are appended or inserted, the array of references is
resized. Some cleverness is applied to improve the performance of
appending items repeatedly; when the array must be grown, some extra
space is allocated so the next few times don’t require an actual
resize.
Like javascript, Python's lists are not required to be homogeneous, so they are not an actual implementation of other "strong typed" data structures that does have to contain only the same entities such as integers, strings, etc.
Same as javascript, the specifications of the language the actual implementation are two separate things. Depending on if you are using Cpython, Jython, IronPython, etc, the memory management and the actual functions that runs behind the scenes will be making diferent things in the process of interpreting python to machine code.
I know that this isnt the best source, but as I found discussed in Quora:
Contrary to what their name implies, Python lists are actually arrays(...).
Specifically, they are dynamic arrays with exponential
over-allocation, which allows code like the following to have linear
complexity:
lst = []
for i in xrange(0, 100000):
lst.append(i)
Alternative implementations like Jython and IronPython seem to use
whatever native dynamic array class their underlying language
(respectively Java and C#) provides, so they have the same performance
characteristics (the precise underlying classes seem to be ArrayList
for Jython and C# List for IronPython).
(...)arrays technically store pointers rather than the objects
themselves, which allows the array to contain only elements of a
specific size. Having pointers all over the place in the underlying
implementation is a common feature of dynamically typed languages, and
in fact of any language that tries to pretend it doesn't have
pointers.
Dictionaries
As the official docs puts in their "History and Design FAQ"
CPython’s dictionaries are implemented as resizable hash tables.
Compared to B-trees, this gives better performance for lookup (the
most common operation by far) under most circumstances, and the
implementation is simpler.
Dictionaries work by computing a hash code for each key stored in the
dictionary using the hash() built-in function. The hash code varies
widely depending on the key; for example, “Python” hashes to
-539294296 while “python”, a string that differs by a single bit, hashes to 1142331976. The hash code is then used to calculate a
location in an internal array where the value will be stored. Assuming
that you’re storing keys that all have different hash values, this
means that dictionaries take constant time – O(1), in computer science
notation – to retrieve a key. It also means that no sorted order of
the keys is maintained, and traversing the array as the .keys() and
.items() do will output the dictionary’s content in some arbitrary
jumbled order.
In Conclution
There are two separate things about a language: one involves how it should work, with it syntax, semantics, logic and philosophy. On the other hand you have the actual implementation of that language in a specific runtime, interpreter or compilation.
This way, although (in theory) you have one Python or one Javascript, you could have CPython, IronPython Jython, etc; and in the other hand, you have SpiderMonkey, V8, etc.
But referring to how each runtime implements the language features of Arrays/Lists and Objects/Dictionaries and how analogous they are, it seems that Javascript has chosen a inheritance model based on prototypes that makes everithing a kind of object; so both Objects and Dictionaries are more like a hash table than an actual array.
On the other hand, Python has a more flavores in respect of data structures, both in their libraries and in how the interpreters deal with them, making use of arrays or dynamic arrays to bring to life the Pyton's Lists, and using hash tables for the dictionaries, making them more similar to the objects in javascript.

Categories

Resources