ES6 Object Literal Syntax for Methods - methods

I'm looking at this this page about various shorthand syntaxes in ES6 for declaring methods inside of objects.
I'm not understanding the differences between these two forms:
var foo = {
a() {},
b() {}
};
and
var foo = {
x: (y) => y
};
The article seems to make a clear distinction between these two formats, but doesn't the first one really just become the second? If we wanted to include parameters, we'd just do a(y) {} in the first one.

but doesn't the first one really just become the second?
No. The method syntax is more equivalent to using a function expression:
var foo = {
a: function() {},
};
If you'd assign an arrow function then you won't be able to access the object via this.
And of course an empty function (function() {}) is not the same as the identity function (function(x) { return x; }).
See also
Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?
Methods in ES6 objects: using arrow functions

Related

universal reference as parameter and return type

Universal references as parameter or return type
I read a few articles about universal references but I still don't understand in which cases I might need to use this as a parameter type besides the move constructor. Could someone enlighten me?
void Foo(Bar&& x);
Bar&& Foo();
Under which circumstances would I ever want to have this which I couldn't solve with a simple Bar& to move something?
When to use std::move
Could someone explain me when an explicit std::move is necessary (for parameters and return types) under which circumstances I can expect that the compiler uses it automatically during the optimization phase? For example
struct A { A(A&& src) ... };
A Foo()
{
A a;
...
return a;
}
In this case I might benefit from RVO, so should I even ever consider using std::move for a result? Thanks a lot!
Universal references
The example you've provided doesn't actually use universal references, those are just r-value references. Syntactically, the universal reference is an r-value reference to a parameter of a deduce templated type:
template <typename Bar>
void foo(Bar &&bar);
This is actually different then a regular r-value reference and it is used to solve a perfect forwarding problem. But I assume this isn't what your question is about.
R-value references
In most cases when you want to move the value to or from the function you can simply do it by value:
void foo(Bar b);
...
Bar somebar;
foo(std::move(somebar)); //function argument is move-constructed
/**************************************************************/
Bar foo()
{
Bar somebar;
return somebar; //return value is move-constructed
}
Doing this using l-value reference is actually incorrect:
void foo(Bar &b)
{
Bar somebar = std::move(b); //you "stole" passed value
}
...
Bar somebar;
foo(somebar); //but the caller didn't intend to move his value
Also returning any reference to a local variable is wrong.
The only reason one would use r-value reference instead of passing by value is to allow moving the value without actually moving it one extra time:
Bar &&Foo::foo()
{
return memberBar;
}
...
Foo f;
Bar b = f.foo(); //"b" will be move-constructed
...
f.foo().doBar(); //returned "Bar" value is just used and not moved at all
When to use std::move
You need to use std::move every time you want to move a variable even if it's already an r-value reference:
Foo::Foo(Bar &&bar)
: memberBar(std::move(bar)) //still need to move explicitly!
{
}
You don't need to use std::move when:
Returning a local variable by value
Passing a temporary to a function, e.g. foo(Bar())
Passing non-movable types (those without move-constructor) including primitive types
A common mistake:
Bar *bar = new Bar();
foo(std::move(bar)); //not needed! nothing to move since the pointer is passed and not the object itself
However when using a conditional operator:
Bar foo()
{
Bar somebar;
Bar otherbar;
return std::move(true ? somebar : otherbar); //need to move explicitly!
}

Should we use _.foreach() or better the native for of loop in TypeScript

I just started to work in a new project working with TypeScript. I'm comming from another project that also worked with TypeScript. Since the native for of loop in TypeScript is avaible we decided (old project team) to use this one. Espacialy for me it was much more convenient to write the for of loop, relating to my java background.
Now in the new project they use everywhere the _.foreach() loop to iterate over arrays.
What I am wondering, is there a performance difference between the native typescript for of and the _.foreach()
i've created a little test in jsperf they seam to be more or less exactly same speed...
https://jsperf.com/foreach-vs-forof/12
TypeScript For of
for (let num: string of list){
console.log(num);
}
In JavaScript
var list = "9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9".split();
//Transpiled TypeScript for of | **19,937 ±5.04%
for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
var num = list_1[_i];
console.log("" + num);
}
//lodash | 20,520 ±1.22%
_.forEach(list, function(item) {
console.log("" + item)
});
Imho i would prefer the "native" for of from TypeScript cause its more readable for me.
What do you guys suggest to use? Are there other points to use for of or better _.forEach
I don't have any experience with typescript beyond my reading but I do have quite a bit of experience with ES6/ES2015. for of was and still is part of the ES2015 spec which was finalized. I would read this article on for of from MDN.
Here are some similarities and differences of for of and forEach (and these are just as far as I have found and know of currently):
forEach in lodash works on collections that are Arrays, Objects, or
Strings.
native forEach works on Arrays, Maps, and Sets.
for of works on all Iterables: Arrays, Strings, TypedArrays,
Maps, Sets, DOM collections, and generators.
I would read this chapter on for of from Exploring ES6 (Exploring ES6 is a great read. It's very thorough. It's free online as well.) Some things from it that stand out to me as different about for of that aren't in forEach.
break and continue work inside for-of loops
break and continue aren't exposed in forEach. The closest thing you can get to continue in forEach is using return which is actually pretty much the same thing. As for break though I see no alternative (but don't discount lodash, because most things that need breaks like finding and returning a single item are already covered in much of lodash's library).
It should also be noted that the await keyword from async/await is usable inside for of where as forEach makes it quite a bit harder to stop the surrounding block from waiting on Promises awaited within the forEach block however it is possible to use forEach although using a map or reduce may make awaiting much simpler than forEach (depending on your familiarity with those functions). Below is three separate implementations of awaiting promises both sequentially and in parallel using, for of, forEach, and reduce and map just to see the possible differences.
const timeout = ms => new Promise(res => setTimeout(() => res(ms), ms));
const times = [100, 50, 10, 30];
async function forOf() {
console.log("running sequential forOf:");
for (const time of times) {
await timeout(time);
console.log(`waited ${time}ms`);
}
console.log("running parallel forOf:");
const promises = [];
for (const time of times) {
const promise = timeout(time).then(function(ms) {
console.log(`waited ${ms}ms`);
});
promises.push(promise);
}
await Promise.all(promises);
};
async function forEach() {
console.log("running sequential forEach:");
let promise = Promise.resolve();
times.forEach(function(time) {
promise = promise.then(async function() {
await timeout(time);
console.log(`waited ${time}ms`);
});
});
await promise;
console.log("running parallel forEach:");
const promises = [];
times.forEach(function(time) {
const promise = timeout(time).then(function(ms) {
console.log(`waited ${ms}ms`);
});
promises.push(promise);
});
await Promise.all(promises);
};
async function reduceAndMap() {
console.log("running sequential reduce:");
const promise = times.reduce(function(promise, time) {
return promise.then(async function() {
await timeout(time);
console.log(`waited ${time}ms`);
});
}, Promise.resolve());
await promise;
console.log("running parallel map:");
const promises = times.map(async function(time) {
const ms = await timeout(time)
console.log(`waited ${ms}ms`);
});
await Promise.all(promises);
}
forOf().then(async function() {
await forEach();
await reduceAndMap();
}).then(function() {
console.log("done");
});
With Object.entries which arrived in ES2017 you can even iterate objects own enumerable properties and values with ease and accuracy. If you want to use it now you can with one of the polyfills here. Here's an example of what that would look like.
var obj = {foo: "bar", baz: "qux"};
for (let x of Object.entries(obj)) { // OK
console.log(x); // logs ["foo", "bar"] then ["baz", "qux"]
}
and here's an implementation with a quick polyfill I wrote. You would normally use array destructuring as well which would seperate the key and value into it's own variables like this:
var obj = {foo: "bar", baz: "qux"};
for (let [key, val] of Object.entries(obj)) { // OK
console.log(key + " " + val); // logs "foo bar" then "baz qux"
}
You can also use Object.entries with forEach like so:
var obj = {foo: "bar", baz: "qux"};
console.log("without array destructuring");
Object.entries(obj).forEach((x) => { // OK
const key = x[0], val = x[1];
console.log(key + " " + val); // logs "foo bar" then "baz qux"
});
console.log("with array destructuring");
Object.entries(obj).forEach(([key, val]) => { // OK
console.log(key + " " + val); // logs "foo bar" then "baz qux"
});
forEach's first argument defaults to the type of functionality you would get from let in a for or for of loop which is a good thing. What I mean by that is if there is anything asynchronous going on inside the variable for that iteration will be scoped to just the particular part of that loop. This property of forEach is not really to do with let, but with scope and closures of functions in JavaScript, and the alternative is due to their not being block scoping. For example see what happens here when var is used:
const arr = [1,2,3,4,5,6,7,8,9];
for(var item of arr) {
setTimeout(() => {
console.log(item);
}, 100);
}
As opposed to when let or foreach is used.
const arr = [1,2,3,4,5,6,7,8,9];
const timeout = 100;
console.log('for of');
for(let item of arr) {
setTimeout(() => {
console.log(item);
}, timeout);
}
setTimeout(() => {
console.log('foreach');
arr.forEach((item) => {
setTimeout(() => {
console.log(item);
}, timeout);
})
}, timeout*arr.length);
Again, I will note the difference between using var and using let or foreach. The difference is that var's variable is hoisted up to the top of the function scope (or file if it's not in a function) and then the value is reassigned for that whole scope, so the loop reaches its end and assigns item for the last time and then every settimeout function logs that last item. Whereas with let and foreach the variable item does not get overwritten, because item is scoped to the block (when let is used) or the function (when foreach is used).
Between forEach and for of you just need to decide which one is best for the current job (e.g. Do you need breaks or need to use Maps, Sets or Generators use for of). Besides that I feel like there aren't particularly strong reasons for either on collections they both operate on with their core functionalities. Also when dealing with collections that can use either forEach or for of it's mainly just up to personal preference as they do the same thing at about the same speed (and the speeds could change at any time according to the interpreter). I feel the particular advantages of lodash are for its other various functions which could actually save you a lot of time from writing the code yourself like map, reduce, filter, and find. Since you feel most comfortable writing for of I suggest you continue writing it that way but once you start writing in lodash using its other functions you may start to feel more comfortable writing it the lodash way.
Edit:
Looking over your code I noticed an error with your list creation. At the end you just had .split() and you should have had .split(","). You were creating a list of length 1 of the whole string and iterating one time on that string that is why the bench marks were so similar. I reran the tests. Here they are. I still wouldn't worry about the performance that much it seems to change every time it's ran.
Based on your test I added another, using the native Array.prototype.forEach :
list.forEach(function(item) {
console.log("" + item)
});
This is infact my preferred way since it is actually much easier to type. Also its closer to other things you might want to do with array e.g. map/filter etc.
Note that http://jsperf.com/foreach-vs-forof/9 all three have no plausible performance difference.
I can't comment on lodash, I haven't used it. But below is some background that may help.
'For of' was introduced in TypeScript 1.5 for looping around each element in e.g. an array list. If you examine the JS output (and depending on if you are targeting ECMA Script 5 or 6), you should find that in the case of ECMASCript5 the output of both the below will be identical. See this article for associated background reading and how targeting ES6/2015 will affect the output.
As for the Typescript implementation of ForEach, there is an interesting discussion over on GitHub here on this. Especially around conditional break out of loop.
for (let line of v.lineEntry) {
}
for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
}

Variable capture by closures in Swift and inout parameters

I noticed that when a variable is captured by a closure in Swift, the closure can actually modify the value. This seems crazy to me and an excellent way of getting horrendous bugs, specially when the same var is captured by several closures.
var capture = "Hello captured"
func g(){
// this shouldn't be possible!
capture = capture + "!"
}
g()
capture
On the other hand, there's the inout parameters, which allow a function or closure to modify its parameters.
What's the need for inout, even captured variables can already be modified with impunity??!!
Just trying to understand the design decisions behind this...
Variables from an outer scope that are captured aren't parameters to the routine, hence their mutablility is inherited from context. By default actual parameters to a routine are constant (let) and hence can't be modified locally (and their value isn't returned)
Also note that your example isn't really capturing capture since it's a global variable.
var global = "Global"
func function(nonmutable:Int, var mutable:Int, inout returnable:Int) -> Void {
// global can be modified here because it's a global (not captured!)
global = "Global 2"
// nomutable can't be modified
// nonmutable = 3
// mutable can be modified, but it's caller won't see the change
mutable = 4
// returnable can be modified, and it's caller sees the change
returnable = 5
}
var nonmutable = 1
var mutable = 2
var output = 3
function(nonmutable, mutable, &output)
println("nonmutable = \(nonmutable)")
println("mutable = \(mutable)")
println("output = \(output)")
Also, as you can see, the inout parameter is passed differently so that it's obvious that on return, the value may be different.
David's answer is totally correct, but I thought I'd give an example how capture actually works as well:
func captureMe() -> (String) -> () {
// v~~~ This will get 'captured' by the closure that is returned:
var capturedString = "captured"
return {
// The closure that is returned will print the old value,
// assign a new value to 'capturedString', and then
// print the new value as well:
println("Old value: \(capturedString)")
capturedString = $0
println("New value: \(capturedString)")
}
}
let test1 = captureMe() // Output: Old value: captured
println(test1("altered")) // New value: altered
// But each new time that 'captureMe()' is called, a new instance
// of 'capturedString' is created with the same initial value:
let test2 = captureMe() // Output: Old value: captured
println(test2("altered again...")) // New value: altered again...
// Old value will always start out as "captured" for every
// new function that captureMe() returns.
The upshot of that is that you don't have to worry about the closure altering the captured value - yes, it can alter it, but only for that particular instance of the returned closure. All other instances of the returned closure will get their own, independent copy of the captured value that they, and only they, can alter.
Here are a couple of use cases for closures capturing variables outside their local context, that may help see why this feature is useful:
Suppose you want to filter duplicates out of an array. There’s a filter function that takes a filtering predicate and returns a new array of only entries matching that predicate. But how to pass the state of which entries have already been seen and are thus duplicates? You’d need the predicate to keep state between calls – and you can do this by having the predicate capture a variable that holds that state:
func removeDupes<T: Hashable>(source: [T]) -> [T] {
// “seen” is a dictionary used to track duplicates
var seen: [T:Bool] = [:]
return source.filter { // brace marks the start of a closure expression
// the closure captures the dictionary and updates it
seen.updateValue(true, forKey: $0) == nil
}
}
// prints [1,2,3,4]
removeDupes([1,2,3,1,1,2,4])
It’s true that you could replicate this functionality with a filter function that also took an inout argument – but it would be hard to write something so generic yet flexible as the possibilities with closures. (you could do this kind of filter with reduce instead of filter, since reduce passes state from call to call – but the filter version is probably clearer)
There is a GeneratorOf struct in the standard library that makes it very easy to whip up sequence generators of various kinds. You initialize it with a closure, and that closure can capture variables to use for the state of the generator.
Suppose you want a generator that serves up a random ascending sequence of m numbers from a range 0 to n. Here’s how to do that with GeneratorOf:
import Darwin
func randomGeneratorOf(#n: Int, #from: Int) -> GeneratorOf<Int> {
// state variable to capture in the closure
var select = UInt32(n)
var remaining = UInt32(from)
var i = 0
return GeneratorOf {
while i < from {
if arc4random_uniform(remaining) < select {
--select
--remaining
return i++
}
else {
--remaining
++i
}
}
// returning nil marks the end of the sequence
return nil
}
}
var g = randomGeneratorOf(n: 5, from: 20)
// prints 5 random numbers in 0..<20
println(",".join(map(g,toString)))
Again, it’s possible to do this kind of thing without closures – in languages without them, you’d probably have a generator protocol/interface and create an object that held state and had a method that served up values. But closure expressions allow a flexible way to do this with minimal boiler plate.
A closure being able to modify the captured variable in the outer scope is pretty common across languages. This is the default behavior in C#, JavaScript, Perl, PHP, Ruby, Common Lisp, Scheme, Smalltalk, and many others. This is also the behavior in Objective-C if the outer variable is __block, in Python 3 if the outer variable is nonlocal, in C++ if the outer variable is captured with &

what does "()" in programming mean? As an example: getche() I understand what getche does, but why the () at the end?

As an example: getche() I understand what getche does, but why the () at the end?
If you are not putting anything in the parenthesis, why do you need them to be there? Just because of standards?
Thanks
Whether a function/method call needs to have parentheses at the end is a syntax particularity that varies from language to language. In Ruby, for example, you don't need it, while in Java, you do.
The compiler can use it to determine that you're making a function/method call. In many languages, you can reference a function as an object, so you need the parentheses to distinguish a reference to a function from a call to a function.
For example, in javascript:
function something(){
return "hello";
}
var a = something;
var b = something();
The variable a will contain the actual function something, while the variable b will contain "hello".
It executes the function without passing any parameters.
In languages with first-class functions, foo and foo() have different meanings. Consider these two examples, in Lua:
local bar = foo -- Assigns foo to bar. bar is now the function at foo.
local bar = foo() -- Executes foo, and assigns the return value to bar.
This, of course, depends on the language you are using. For example, in Haskell, no parenthesis are used to call functions.
This is syntax for Method/function.
Why is the need of it ? Because in the () you can provide the input arguments as well.
like for example :
var sum = addition(3,4);
Here addition can be defined as:
int addition(int a, int b)
{
return (a+b);
}

A list of predefined groovy variables

I'm new to groovy and I'm wondering where can I find a full list of predefined
groovy variables like it and delegate?
The particular thing that I'm interested in is if there are predefined keyword for
the reference to the object from where the current method was invoked, for example:
5.times { print 5 - it}
with the use of such keyword it should be something like:
5.times { print *keyword* - it }
so the question is what's the keyword should be used there?
P.S.: another example:
MyObject myObject = new myObject();
myObject.getField(); // MyObject has method named getField
myObject.doJob ({
...
((MyObject)*keyword*).getField(); // instead of myObject.getField();
...
})
For a good list of all actual keywords (which are fewer than you'd think) and object-level properties that are like keywords, this article is really good: http://marxsoftware.blogspot.com/2011/09/groovys-special-words.html
If you have control over the doJob method in your example, then you should set the delegate of the closure:
def doJob(Closure closure) {
closure.delegate = this
closure.resolveStrategy = Closure.DELEGATE_FIRST
// loop or whatever
closure()
}
Now, in your closure, you can reference any properties on the parent object directly, like so:
myObject.doJob ({
...
getField()
...
})
Groovy Closures - Implicit Variables.
Are you asking for this?
int number = 5
number.times { print number - it }
Hope this will help you

Resources