ecmascript-6 , Is there any way to modify a Set data structure in iteration (ECMAScript 6)?


Is there any way to modify a Set data structure in iteration (ECMAScript 6)?

Question:

Tag: ecmascript-6

The Set object in ES6 has a forEach method, just like Array object does. Is there any way to modify the values when iterating over the Set object using the forEach method?

For example:

// Array object in ES5 can be modified in iteration
var array = [1, 2, 3];
array.forEach(function(int, idx, a) {
    a[idx] = int * int;
});
array;  // => [1, 4, 9]

But when iterating over a Set object,

// Set will not be updated
var set = new Set([1, 2, 3]);
set.forEach(function(val1, val2, s) {
    val2 = val1 * val1;
})
set;   // => [1, 2, 3]

Is there any way to achieve the same effect as Array object?


Answer:

I'd probably do

var set = new Set([1, 2, 3]);
set = new Set(Array.from(set, val => val * val));

to just make a new set with the new values, and replace the old. Mutating the set as you iterate over it is a bad idea and seems like it's easy to avoid in your usecase.


Related:


How to get a last element of ES6 Map without iterations?


containers,ecmascript-6
How to get a last element of ES6 Map/Set without iterations(forEach or for of) pass through a full length of the container?

How to check if a variable is an ES6 class declaration?


javascript,class,prototype,ecmascript-6
I am exporting the following ES6 class from one module: export class Thingy { hello() { console.log("A"); } world() { console.log("B"); } } And importing it from another module: import {Thingy} from "thingy"; if (isClass(Thingy)) { // Do something... } How can I check whether a variable is a class?...

“Variable 'X' can be made constant”, what does 'constant' mean?


typescript,resharper,ecmascript-6
VStudio or ReSharper is giving me the suggestion below: What does constant mean in this scenario? If it's a constant in the current method scope, what's the purpose? Methods tend to be small and therefore it shouldn't give any advantage compared to be a regular var? Please enligten me...

Input validation setTimeout in ReactJS


javascript,css,validation,reactjs,ecmascript-6
I have a component that renders with className="error" or classname="" depending on whether the input is valid or not. This way in CSS I can simply do .error { background: red; }. The validity of the input is determined by the isValidNumber(..) function. However, right now the problem I'm having...

Sequential Loading Using Promises


javascript,promise,ecmascript-6,bluebird,es6-promise
I've got an array of asynchronous calls that I want to be called sequentially, meaning that I don't want to call the second promise until the first is complete, and so on. In the following example, I've got a loop that creates unique images on the fly and appends them...

Unit testing with Karma on an Angular 1.3/JSPM/Babel project


angularjs,karma-runner,ecmascript-6,jspm
So I'm setting up an angular 1.3 es6 project using jspm and babel. Im using es6's import/export feature. I have karma and karma-jspm installed and can run basic tests without an issue. When I try to import one of my modules into a test to test it, I get an...

Shallow-clone an ES6 Map or Set


javascript,ecmascript-6
How do you shallow-clone an ES6 Map or Set object? I want to get a new Map or Set that has the same keys and values....

Mixins for ES6 classes, transpiled with babel


javascript,mixins,ecmascript-6
According to various sources (2ality, esdiscuss) one should be able to add mixins to classes: EDIT discovered that class methods are not enumerable so that cannot work. Edited the code below, but still no joy class CartoonCharacter { constructor(author) { this.author = author; } drawnBy() { console.log("drawn by", this.author); }...

Is there any way to modify a Set data structure in iteration (ECMAScript 6)?


ecmascript-6
The Set object in ES6 has a forEach method, just like Array object does. Is there any way to modify the values when iterating over the Set object using the forEach method? For example: // Array object in ES5 can be modified in iteration var array = [1, 2, 3];...

Do I have to call super.componentDidUpdate in React?


reactjs,ecmascript-6
In a subclass of React.Component, do I have to call super.componentDidUpdate from my componentDidUpdate method? Or is it done automatically? (I am trying to call it but there is an error message Cannot read property call of undefined)...

Explanation of `let` and block scoping with for loops


javascript,ecmascript-6
I understand that let prevents duplicate declarations which is nice. let x; let x; // error! Variables declared with let can also be used in closures which can be expected let i = 100; setTimeout(function () { console.log(i) }, i); // '100' after 100 ms What I have a bit...

Writing the most basic Unit test in Angular 2?


javascript,unit-testing,karma-runner,ecmascript-6,angular2
Problem: As soon as I import Angular 2 into a file none of my tests execute. Question: How can I set up my karma config to support angular two so my test pass properly? OR Question: How can I set up any testing framework with angular2 written in es6? Git...

ES6 Iterate over class methods


javascript,ecmascript-6
Given this class; how would i iterate over the methods that it includes? class Animal { constructor(type){ this.animalType = type; } getAnimalType(){ console.log('this.animalType: ', this.animalType ); } } let cat = window.cat = new Animal('cat') What I have tried is the following with no success: for (var each in Object.getPrototypeOf(cat)...

What's the purpose of allowing duplicate property names?


javascript,standards,ecmascript-6
I'm reading the MDN javascript reference, accordingly the following code no longer returns false: function haveES6DuplicatePropertySemantics(){ "use strict"; try { ({ prop: 1, prop: 2 }); // No error thrown, duplicate property names allowed in strict mode return true; } catch (e) { // Error thrown, duplicates prohibited in strict...

ServiceWorker and Push Notification Payload


node.js,android-gcm,ecmascript-6,service-worker,chrome-gcm
Community: ServiceWorker is a great advance technology in terms of cache managment, but I have some questions associated with other operations such as: Push Notification: I made a GCM integration (Google Clud Message) and NodeJS, following this article, the problem is that when GCM sends the information to the client...

Create a subset object, consisting of only some of the properties of an existing object


javascript,ecmascript-6
This is best explained by example. The following works in es6 to create an object consisting of some of the keys of an existing object: var o = {a:1, b: 2, c: 3} var {a, c} = o var subsetObj = {a, c} // will be: {a:1, c:3} There are...

ES6 read-only enums that can map value to name


enums,ecmascript-6
I would like to define an enum-like structure in JS, but have two requirements: The values be read-only, i.e. no users can assign to them. The values (0, 1, 2, ...) can be mapped back into the names (as with Java's name method) The methods I know to create enums...

how to correctly use promises to return 2 different results [duplicate]


javascript,promise,ecmascript-6,es6-promise
This question already has an answer here: How do I access previous promise results in a .then() chain? 6 answers I am trying to use Promises in JavaScript using ES6 to return data from 2 methods from an object, which would in production call out to an endpoint. My...

Symbol.for(string) in ECMAScript 6


javascript,symbols,ecmascript-6
It took me a while but I finally figured out what the purpose of symbols in ECMAScript 6 is: avoiding name collision when attaching properties to shared objects - HTML elements e.g. (In case you're stuck on the same question, I recommend this article.) But then I stumbled upon Symbol.for()....

How to properly bind current object context in ES6 using babelify


ecmascript-6,babel
I'm trying to bind current instance to the class method, please note ES6 syntax. class SomeClass { search() => { ... } } Which is 100% legit code, however babelify doesn't want to compile it SyntaxError: /Users/vladmiller/Projects/test/test/client/test/app/pages/Search.react.js: Unexpected token (50:26) while parsing file: /Users/vladmiller/Projects/test/test/client/test/app/pages/Search.react.js\ Instead now I have to bind...

Import non modular scripts (linq.js) in Aurelia


ecmascript-6,aurelia
I have a question about importing script which define global variables to aurelia using import keyword. We can simple import modules but what about scripts like linq.js which define global variable Enumerable? Is this possible to execute that script to define that namespace? I tried to do steps from this...

ECMAScript class


javascript,ecmascript-6
I have the following code which when the web page loads should print the car make and current speed to the console. Nothing is printed to the console. If I put the new object declaration inside a function it does print either. <!DOCTYPE html> <html> <head> <script type="application/ecmascript;version=6"> class Car...

Include paths for imports in babel using webpack


ecmascript-6,webpack,babeljs
Given a directory structure such as: project ├───common │ └───js └───src └───js is there any way to add import paths to webpack so that a script inside src/js can resolve code inside common/js if it cannot find anything else locally? Something like the code below would include common/js/CommonClass.js: import CommonClass...

functional way to iterate over range (ES6/7) [duplicate]


javascript,ecmascript-6,ecmascript-harmony
This question already has an answer here: Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables? 5 answers What is the best way to do the below in more functional way (with ES6/ES7) let cols = []; for (let i =0; i <=...

Why should I use ES6 classes? [closed]


javascript,ecmascript-6
I have many question about ES6 classes. Since i understand how to use function and WebComponent, React & so. I didn't see many benefit using it. I wonder what's the benefit of using classes. I read that public/private/static will be part of ES7. So i see no point using it...

why obj={x,y} works in Chrome?


javascript,ecmascript-6
var obj = { type: 'data', x, y, data: []} Obviously this was my typo, {x,y} should have been {x:x, y:y}. But it does what I want, in Chrome, field x gets the value of a local variable x. But why does it work?...

Change the value of a key in ES6 constructor


javascript,class,prototype,ecmascript-6
Question: How do I write a proper prototypical function using classes in ES6? How do I make sure that this function will change the value of title key in the constructor of Todo class? class Todo{ constructor(title){ this.title = title; } setTitle(newTitle){ this.title = newTitle; } } var a1 =...

ES2015 Babel String Interpolation not working with apostrophe (but does with double quotes)


javascript,ecmascript-6,babeljs
I am using babel / grunt to learn some ES2015. According to this post there is no real difference in Javascript between single and double quotes. i.e. 'test' and "test". When trying string interpolation though, it seems there is an issue with babeljs (or more likely - me). What is...

MongoDB Object key with ES6 template string


javascript,mongodb,ecmascript-6
I'm trying to update an array in my collection with this: var str = "list.0.arr"; db.collection('connect').update({_id: id}, {$push: { `${str}`: item}}); This exact string works just fine if I do it like this: db.collection('connect').update({_id: id}, {$push: { "list.0.arr": item}}); This is to show that it works, but It's throwing an...

Prototype chains in ECMAScript 6


javascript,subclass,ecmascript-6,ecmascript-harmony
I recently came across this great post by Dr. Axel Rauschmayer: http://www.2ality.com/2015/02/es6-classes-final.html The following snippet roughly describes how ECMAScript 6 prototype chains work from an ECMAScript 5 point of view (section 4.2 of the original post): // ECMAScript 6 class Point { constructor(x, y) { this.x = x; this.y =...

ES6: call class constructor without new keyword


javascript,ecmascript-6
Given a simple class class Foo { constructor(x) { if (!(this instanceof Foo)) return new Foo(x); this.x = x; } hello() { return `hello ${this.x}`; } } Is it possible to call the class constructor without the new keyword? Usage should allow (new Foo("world")).hello(); // "hello world" Or Foo("world").hello(); //...

Dynamic key in immutability update helper for array


javascript,reactjs,ecmascript-6
https://facebook.github.io/react/docs/update.html I have an update function that receives an index along with the event so as to alter the value for that specific item in the array. How do I get index to be evaluated instead of treated as a set key in this scenario? Is it even possible? updateValue:...

Inheriting defaultProps from superclass in React


inheritance,reactjs,ecmascript-6
I think some props, like "theme", are so universal among components that it makes sense to extract their handling (to a superclass). Then it follows that their default value also belongs there. However, using React this doesn't seem possible: class Base extends React.Component { bgColor() { switch (this.props.theme) { case...

IntelliJ/Webstorm not finding import reference


javascript,intellij-idea,phpstorm,webstorm,ecmascript-6
I have the following project structure: root src scripts main.js foo.js Inside of my main.js file, I'm importing foo.js like so: import 'src/scripts/foo.js' When I click on the import statement above and go to Navigate -> Declaration I get a super helpful message that says Cannot find declaration to go....

“Import” ES6 for Node


javascript,node.js,ecmascript-6
I want to use import from ES6 rather than require from common.js in Node. For some reason I thought import would work by default in Node. But looks like it does not. Is there some npm package i need to install for that to work?

How do I support jasmine and es6 syntax in Visual studio Code?


jasmine,ecmascript-6,vscode
Question where can I find and how do I add support for jasmine and es6 syntax in Visual studio code? ...

Promise.allSettled in babel ES6 implementation


javascript,node.js,ecmascript-6,babel,es6-promise
I'm using babel to transpile my [email protected] code and I'm stuck with promises. I need allSettled-type functionality that I could use in q and bluebird or angular.$q for example. On babel's core-js Promise, there is no allSettled method. Currently I'm using q.allSettled as a workaround: import { allSettled } from...

Using String.raw() with Node JS


javascript,node.js,ecmascript-6
I'm working on a Node.js app with and I would like to use String.raw() which is part of the ES 6 standard. However, when using it as in the documentation: text = String.raw`Hi\n${2+3}!` + text.slice(2); It returns SyntaxError: Unexpected token ILLEGAL for the character after String.raw. I think that there...

Obj-C category/extension Swift in Javascript ES6


javascript,ecmascript-6
I'm looking to add methods to a class in Javascript ES6 without creating a subclass of it, in the same way with the categories in Objective-C or extensions in Swift. I didn't find any information about it. Any suggestion?...

Angular 1.4 + ngNewRouter + ES6 : Cannot read property '$routeConfig' of undefined


angularjs,ecmascript-6,angular-new-router
I am currently trying to throw together a basic working example of an Angular 1.4 app written with both the new router as well as ECMAScript 6. I have been fiddling with this code non stop and I don't understand why I am getting the error that is being thrown:...

How to test if browser supports js ES6 Class? [duplicate]


javascript,class,ecmascript-6,browser-support
This question already has an answer here: Javascript ES6 cross-browser detection 2 answers My js classes works fine in Chrome, but when I test in IE for example, the script fails as expected, giving an ugly syntax error. Is there someway to test if the clients browser can handle...

Executing promises in sequence: understanding a claim made about this example code


javascript,promise,ecmascript-6
I'm not looking for a solution for how to execute promises in sequence, I'm trying to understand the one given by a blog author: I am reading "We have a problem with promises" by Nolan Lawson, posted 18 May 2015. Under "Advanced mistake #3: promises vs promise factories" he has...

Compile a directory tree of separate apps (one entry point each), using CommonJS modules and ES6 modules


build,couchdb,ecmascript-6,commonjs
I am writing a Couch app. The output of the build process must be a directory tree of self contained JS files, like so: dist ├── _attachments │ ├── logo.jpg │ └── splash.jpg ├── lists │ └── sitemap.js ├── shows │   ├── article.js │ ├── home.js │ └── dashboard.js ├──...

Aurelia update value of bound item in another class


ecmascript-6,aurelia
I guess the question boils down how to i pass the instance of a property to another class. I have something like this: import timerClass from "./timer"; export class App { constructor() { this.timeLeft = 6; //<--- I want to update this new timerClass(this.timeLeft); } activate() { } } and...

ES6 destructuring, dynamic assignment [duplicate]


javascript,ecmascript-6
This question already has an answer here: object destructuring without var 1 answer let text, value; if (typeof f == 'string') { text = value = f; } else { let { text, value } = f; } Doing this creates two new vars (from the else), however if...

can es6 class have public properties as well as functions?


javascript,class,properties,public,ecmascript-6
All the examples of classes I see are class myClass{ constructor(){} someFunction(){} what I want to add is someObject {myvalue:value} } this doesn't seem to compile. An old fashioned object would be { somefunction: function(){} someProperty: {myvalue:value} } is this not possible in es6 classes?...

React components as plain JS objects?


javascript,class,reactjs,javascript-objects,ecmascript-6
Does anybody has experience in working with React components as plain JS objects instead of annoying ES6 classes and deprecated .createClass method. Maybe you have some examples of factory functions or similar to share? Thanks!...

ES6 - Convert from 'require' to 'import'


ecmascript-6
If the alternative to: var Foo = require('foo'); is: import Foo from 'foo'; What is the alternative to: var Bar = require('foo').batz Could it be: import {batz} from 'foo' ? ...

Automatically call bind() on all instance methods in es6 during constructor


javascript,ecmascript-6
How can I (or is it possible to) make a JavaScript base class that automatically calls bind on each of its instance methods during it's constructor? I tried, without success: class BaseClass { constructor() { // for (let i in this.__proto__) { // <-- this also failed for (let i...

How does `this` work in default parameters?


javascript,ecmascript-6
So... ES6¹ (which happens to be standardized a few hours ago) brings default parameters for functions similar to those in PHP, Python etc. I can do stuff like: function foo (bar = 'dum') { return bar; } foo(1); // 1 foo(); // 'dum' foo(undefined); // 'dum' MDN says that the...