Elvis Miranda

Elvis Miranda

1576508119

Es6 Collection Map, Set, WeakMap, WeakSet

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: Map, Set, WeakSet, and WeakMap.

Searching for the JavaScript HashMap

HashMaps, dictionaries, and hashes are several ways that various programming languages store key/value pairs, and these data structures are optimized for fast retrieval.

In ES5, JavaScript objects — which are just arbitrary collections of properties with keys and values — can simulate hashes, but there are several downsides to using objects as hashes.

Downside #1: Keys must be strings in ES5

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.

Downside #2: Objects are not inherently iterable

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. (See, for example, Object.keys is slow). When you loop over an object’s properties, you also get its prototype properties. You could add the iterable property to all objects, but not all objects are meant to be used as collections. You could use the for … in loop and the hasOwnProperty() 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.

Downside #3: Challenges with built-in method collisions

Objects have built-in methods like constructor, toString, and valueOf. If one of these was added as a property, it could cause collisions. You could use Object.create(null) to create a bare object (which doesn’t inherit from object.prototype), but, again, this is just a workaround.

ES6 includes new collection data types, so there’s no longer a need to use objects and live with their drawbacks.

Using ES6 Map Collections

Map 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:

Creating a map and using common methods

const map = new Map(); // Create a new Map
map.set('hobby', 'cycling'); // Sets a key value pair

const foods = { dinner: 'Curry', lunch: 'Sandwich', breakfast: 'Eggs' }; // New Object
const normalfoods = {}; // New Object

map.set(normalfoods, foods); // Sets two objects as key value pair

for (const [key, value] of map) {
  console.log(`${key} = ${value}`); // hobby = cycling  [object Object] = [object Object]
}

map.forEach((value, key) => {
  console.log(`${key} = ${value}`);
}, map); // hobby = cycling  [object Object] = [object Object]

map.clear(); // Clears key value pairs
console.log(map.size === 0); // True

Run this example on JSBin

Using the Set Collection

Sets are ordered lists of values that contain no duplicates. Instead of being indexed like arrays are, sets are accessed using keys. Sets already exist in Java, Ruby, Python, and many other languages. One difference between ES6 Sets and those in other languages is that the order matters in ES6 (not so in many other languages). Here are the crucial Set methods:

const planetsOrderFromSun = new Set();
planetsOrderFromSun.add('Mercury');
planetsOrderFromSun.add('Venus').add('Earth').add('Mars'); // Chainable Method
console.log(planetsOrderFromSun.has('Earth')); // True

planetsOrderFromSun.delete('Mars');
console.log(planetsOrderFromSun.has('Mars')); // False

for (const x of planetsOrderFromSun) {
  console.log(x); // Same order in as out - Mercury Venus Earth
}
console.log(planetsOrderFromSun.size); // 3

planetsOrderFromSun.add('Venus'); // Trying to add a duplicate
console.log(planetsOrderFromSun.size); // Still 3, Did not add the duplicate

planetsOrderFromSun.clear();
console.log(planetsOrderFromSun.size); // 0

Run this example on JSBin

Weak Collections, Memory, and Garbage Collections

JavaScript Garbage Collection is a form of memory management whereby objects that are no longer referenced are automatically deleted and their resources are reclaimed.

Map and Set‘s references to objects are strongly held and will not allow for garbage collection. This can get expensive if maps/sets reference large objects that are no longer needed, such as DOM elements that have already been removed from the DOM.

To remedy this, ES6 also introduces two new weak collections called WeakMap and WeakSet. These ES6 collections are ‘weak’ because they allow for objects which are no longer needed to be cleared from memory.

WeakMap

WeakMap is the third of the new ES6 collections we’re covering. WeakMaps are similar to normal Maps, albeit with fewer methods and the aforementioned difference with regards to garbage collection.

const aboutAuthor = new WeakMap(); // Create New WeakMap
const currentAge = {}; // key must be an object
const currentCity = {}; // keys must be an object

aboutAuthor.set(currentAge, 30); // Set Key Values
aboutAuthor.set(currentCity, 'Denver'); // Key Values can be of different data types

console.log(aboutAuthor.has(currentCity)); // Test if WeakMap has a key

aboutAuthor.delete(currentAge); // Delete a key

Run this example on JSBin

Use cases

WeakMaps have several popular use cases. They can be used to keep an object’s private data private, and they can also be used to keep track of DOM nodes/objects.

Private data use case

The following example is from JavaScript expert Nicholas C. Zakas:

var Person = (function() {
  var privateData = new WeakMap();

  function Person(name) {
    privateData.set(this, { name: name });
  }

  Person.prototype.getName = function() {
    return privateData.get(this).name;
  };

  return Person;
}());

Using a WeakMap here simplifies the process of keeping an object’s data private. It’s possible to reference the Person object, but access to the privateDataWeakMap is disallowed without the specific Person instance.

DOM nodes use case

The Google Polymer project uses WeakMaps in a piece of code called PositionWalker.

PositionWalker keeps track of a position within a DOM subtree, as a current node and an offset within that node.

WeakMap is used to keep track of DOM node edits, removals, and changes:

_makeClone() {
  this._containerClone = this.container.cloneNode(true);
  this._cloneToNodes = new WeakMap();
  this._nodesToClones = new WeakMap();

  ...

  let n = this.container;
  let c = this._containerClone;

  // find the currentNode's clone
  while (n !== null) {
    if (n === this.currentNode) {
    this._currentNodeClone = c;
    }
    this._cloneToNodes.set(c, n);
    this._nodesToClones.set(n, c);

    n = iterator.nextNode();
    c = cloneIterator.nextNode();
  }
}

WeakSet

WeakSets are Set Collections whose elements can be garbage collected when objects they’re referencing are no longer needed. WeakSets don’t allow for iteration. Their use cases are rather limited (for now, at least). Most early adopters say that WeakSets can be used to tag objects without mutating them. ES6-Features.org has an example of adding and deleting elements from a WeakSet in order to keep track of whether or not the objects have been marked:

let isMarked     = new WeakSet()
let attachedData = new WeakMap()

export class Node {
    constructor (id)   { this.id = id                  }
    mark        ()     { isMarked.add(this)            }
    unmark      ()     { isMarked.delete(this)         }
    marked      ()     { return isMarked.has(this)     }
    set data    (data) { attachedData.set(this, data)  }
    get data    ()     { return attachedData.get(this) }
}

let foo = new Node("foo")

JSON.stringify(foo) === '{"id":"foo"}'
foo.mark()
foo.data = "bar"
foo.data === "bar"
JSON.stringify(foo) === '{"id":"foo"}'

isMarked.has(foo)     === true
attachedData.has(foo) === true
foo = null  /* remove only reference to foo */
attachedData.has(foo) === false
isMarked.has(foo)     === false

Map All Things? Records vs ES6 Collections

Maps and Sets are nifty new ES6 collections of key/value pairs. That said, JavaScript objects still can be used as collections in many situations. No need to switch to the new ES6 collections unless the situation calls for it.

MDN has has a nice list of questions to determine when to use an object or a keyed collection:

  • Are keys usually unknown until run time, and do you need to look them up dynamically?
  • Do all values have the same type, and can be used interchangeably?
  • Do you need keys that aren’t strings?
  • Are key-value pairs often added or removed?
  • Do you have an arbitrary (easily changing) amount of key-value pairs?
  • Is the collection iterated?

New ES6 Collections Yield a More Usable JavaScript

JavaScript collections have previously been quite limited, but this has been remedied with ES6. These new ES6 collections will add power and flexibility to the language, as well as simplify the task of JavaScript developers who adopt them.

#javascript #programming

What is GEEK

Buddha Community

Es6 Collection Map, Set, WeakMap, WeakSet
Joseph  Murray

Joseph Murray

1621559580

Collection vs Collections in Java: Difference Between Collection & Collections in Java

Introduction

This article will be looking into one of the most popular questions in Java Language – What is Collection in Java? Also, what do you mean by Collections in Java? Are Collection and Collections the same or different in Java?

What is Collection?

What is Collections?

Conclusion

#full stack development #collection #collection vs collections in java #collections in java #difference between collection and collections in java

Part 4 : ES6 JavaScript : Map Collection in Javascript | Map Methods | Map vs Object

Javascript  : Map Collection in Javascript | Map Methods | Map vs Object

  • What is Map ?
  • How to Create Map ?
  • Map Methods%
  • Map vs Object

#javascript #map  #collections #objective

https://www.youtube.com/watch?v=cCW-GY6UGJI

Jarrod Howe

Jarrod Howe

1610436780

ES6 Tutorial For Beginners - Sets, Weaksets, Maps, and Weakmaps

Javascript hasn’t had the luxury of having different collections like other programming languages like Java or Python. Well, that was until the release of ES6 which introduced Maps, Weakmaps, Sets, and Weaksets and that’s exactly what I’m covering in this part of the series.

#es6 #javascript #web-development

Kotlin Map collection - map() methods » grokonez

https://grokonez.com/kotlin/kotlin-map-collection-map-methods

Kotlin Map collection – map() methods

In the tutorial, JavaSampleApproach will show you how to use map() methods to transform Kotlin Map collection to Kotlin List collection or a new Map collection.

I. Kotlin Map collection with map() methods

Kotlin Map collection supports a set of map() methods to transform the given map to a new map or a new list:
1. fun <K, V, R> Map<out K, V>.map(transform: (Map.Entry<K, V>) -> R): List<R>
2. fun <K, V, R : Any> Map<out K, V>.mapNotNull(transform: (Map.Entry<K, V>) -> R?): List<R>
3. fun <K, V, R, C : MutableCollection<in R>> Map<out K, V>.mapTo(destination: C, transform: (Map.Entry<K, V>) -> R): C
4. fun <K, V, R : Any, C : MutableCollection<in R>> Map<out K, V>.mapNotNullTo(destination: C, transform: (Map.Entry<K, V>) -> R?): C
5. fun <K, V, R> Map<out K, V>.mapKeys(transform: (Map.Entry<K, V>) -> R): Map<R, V>
6. fun <K, V, R> Map<out K, V>.mapKeys(transform: (Map.Entry<K, V>) -> R): Map<R, V>
7. fun <K, V, R> Map<out K, V>.mapValues(transform: (Map.Entry<K, V>) -> R): Map<K, R>
8. fun <K, V, R, M : MutableMap<in K, in R>> Map<out K, V>.mapValuesTo(destination: M, transform: (Map.Entry<K, V>) -> R): M	

Now practicing ->

0. Initial data for practicing


data class Address(
	val street: String,
	val postcode: String
)

data class Customer(
val firstName: String,
val lastName: String,
val age: Int
)

data class Person(
val fullname: String,
val age: Int,
val address: Address
)

val customerMap = mapOf(Pair(Customer(“Jack”, “Davis”, 25), Address(“NANTERRE CT”, “77471”)),
Pair(Customer(“Mary”, “Taylor”, 37), Address(“W NORMA ST”, “77009”)),
Pair(Customer(“Peter”, “Thomas”,17), Address(“S NUGENT AVE”, “77571”)),
Pair(Customer(“Amos”, “Nelson”,23), Address(“E NAVAHO TRL”, “77449”)),
Pair(Customer(“Craig”, “White”,45), Address(“AVE N”, “77587”)),
Pair(Customer(“Laura”, “Lewis”, 32), Address(“NANTERRE CT”, “77471”)),
Pair(Customer(“Steven”, “Harris”, 39), Address(“S NUGENT AVE”, “77571”)),
Pair(Customer(“Paul”, “Moore”, 18), Address(“E NAVAHO TRL”, “77449”)),
Pair(Customer(“Mary”, “Cook”, 61), Address(“S NUGENT AVE”, “77571”)),
Pair(null, null))

1. Transform a given Kotlin Map to List

1.1 map()

Method signature:

More at:

https://grokonez.com/kotlin/kotlin-map-collection-map-methods

Kotlin Map collection – map() methods

#kotlin #map #collection

sarika Inogic

1623221809

Maplytics - Dynamics 365 CRM and Bing Maps Integration

Maplytics™ is an advanced mapping and data visualization tool for Microsoft Dynamics 365 CRM. It provides Territory Management, Appointment Planning, Routing, Radius Search and much more with support for PowerApps (CDS). Maplytics supports all Dynamics 365 deployment models for Dynamics CRM 2011 and above as well as native Dynamics 365 App for Phones and Tablets.
Below are the features you can avail with Maplytics
• Sales Territory Management: Geographically manage and align sales territories, perform binary operations on shapes, regions or territories on map. Assign multiple territories to a record.
• Auto Scheduling: Create an automated optimized schedule for multiple days on field including routes to follow each day based on details entered by user and also create activities for the same
• Check-In/Check-Out: Enable Check-In/Check-Out for field reps on site of visit with the option of Geofencing
• PCF control: User can add components on fields or grids within Dynamics CRM to view the respective records on the map within the record form or the entity grid
• Overlay: View records, shape files and existing territories together on map. View Census Data as existing Overlay feature.
• Proximity Search: Search records for a location based on radius or time with shortest travel and line of sight distance.
• Route Optimization: Optimize routes, find nearby records along the route and points of interest like Coffee Shops, Gas station, etc.
• Customizable Pushpins & Tooltip Cards: Plot desired icons for pushpins for seamless visual analysis. Call to action buttons on Tooltip cards for quick actions.
• Security template: System admin and Maplytics admin can provide selective access of actions to users
• Marketing Management: Create geographically targeted Marketing Lists for personalized and relevant promotions, marketing campaigns and events
• Mass Actions: Add to Route, Save Data, Schedule Appointments, Send Emails and more for records plotted on map
• Summary Card: Get aggregated information for enclosed area on map for quick analysis
• Layer Menu/Download Map: Show/hide layers plotted on map to toggle between them and Download the map as image visible on screen
• Mobility: Use native Dynamics 365 App for Phones and Tablets to get locational insights
• Heat Map Visualization: Analyze density of CRM data on map for insights through pie/column charts
• Real-Time Tracking: Managers can now track the location of Field Service Reps when on field in real time within Dynamics 365 Field service.
• Land Area Mapping: Define the area of land as agricultural, residential, commercial properties and visualize the same on the map.
• Territory Assignment Rule: Maplytics Admins and Managers can create simple/advanced rules based on which territories will be assigned to the records as per the required conditions.

#maps #bing #maps #map #dyynamics #65crm