Immediately invoked functions in CoffeeScript - coffeescript

Could someone show me how to immediately invoke a function in CoffeeScript. I'm trying to accomplish something similar to this JS object literal.
WEBAPP = {
maxHeight : function(){
/* Calc stuff n' stuff */
WEBAPP.maxHeight = /* Calculated value */
}(),
someProperty : ''
/* ... */
}
Is it possible or what are the workarounds?

There is do:
WEBAPP =
maxheight: do -> 1+1
someProperty: ''
Which compiles to
var WEBAPP;
WEBAPP = {
maxheight: (function() {
return 1 + 1;
})(),
someProperty: ''
};

For anyone else coming across this question, you can also combine the do keyword with default function parameters to seed recursive "immediately-invoked functions" with an initial value. Example:
do recursivelyPrint = (a=0) ->
console.log a
setTimeout (-> recursivelyPrint a + 1), 1000

why won't you try something like this?
square = (x) -> x * x
WEBAPP = {
maxHeight: square(3),
someProperty: ''
}
UPDATE
BTW: this is other workaround
WEBAPP = {
maxHeight: (() ->
1 + 2
)()
}

Related

What does this function actually do?

i am currently trying to do some self learning in swift just for my own interest. in the course i bought it says that we should create a function similar to this one in order to solve my problem. but I'm blankly staring trying to figure out what this function actually does?
func unknown() -> () -> Int {
var x = 0
let z: () -> Int = {
x += 1
return x
}
return z
}
It is a function that returns another function which will return an integer that will be increased everytime you call it:
let afunc = unknown()
let value1 = afunc() // 1
let value2 = afunc() // 2
let value3 = afunc() // 3
The interesting part of this is the return type. () -> Int is a function that returns an Int, which means that unknown returns a function rather than something simple, like a number.
z is then a variable of that same type and is assigned a function definition to be returned.
If you assign the result of unknown to a variable, you can then invoke the returned function.
This implementation of a high order function is an interesting way of defining generators. An infinite sequence-like class would've achieve the same thing, but with more verbosity:
class MySequence {
private var x = 0
func unknown() -> Int {
x += 1
return x
}
}
var seq = MySequence()
let unknown = seq.unknown
print(unknown()) // 1
print(unknown()) // 2
print(unknown()) // 3
// ... and so on
The main difference between the class and the anonymous closure is the storage for x: the closure captures in due to using the variables within its body, while the class declares explicit storage for the property.
Some fancy stuff can result by using high order functions, like a generator for the Fibonacci numbers:
func fibonnaciSequence() -> () -> Int? {
var a = 0, b = 1
return { let c = a; a += b; b = c; return c }
}
let fibo = fibonnaciSequence()
while let f = fibo() {
// this will print forever
// actually not forever, it will stop at some point due to += overflowing
print(f)
}

Is there a way to retrieve directly the value returned from a closure in Swift, with type the return type of the closure and not: () -> Type

This is a question that aims merely at elegance, but is there a way to make something to the following code work in Swift? I know the code does not work, what I want is that the result of the code within the closure is stored in a constant. And the underlying theoretical issue is whether or not it is possible to retrieve the returned value from the closure with type Int and not with type () -> Int.
Thanks a lot for any help or comment!
let tableWithBooleans: [Bool] = Array(repeating: false, count: 10)
tableWithBooleans[0] = true
tableWithBooleans[5] = true
let numberOfTrue: Int = {
var result: Int = 0
for i in 0...9 {
if tableWithBooleans[i] {
result += 1
}
}
return result
}
// I want the code to compile and numberOfTrue to be a constant equal to 2
Use a high-order function instead
let numberOfTrue = tableWithBooleans.reduce(0) { $1 ? $0 + 1 : $0 }
Now if you still want to use your closure code then you should add a () after the closing } since you are calling the code inside {} as a function
let numberOfTrue: Int = {
var result: Int = 0
for i in 0...9 {
if tableWithBooleans[i] {
result += 1
}
}
return result
}()

isEnabled() function not working in Protractor

I want to select a date in calendar picker using protractor. Below is the snippet of code, that I have written in my script:
if (dat <= 24) {
var us_dat = element(by.xpath("(//a[text()='" + dat + "'])[1]"));
} else {
var us_dat = element(by.xpath("(//a[text()='" + dat + "'])[1]"));
if (us_dat.isEnabled() == false) {
var us_dat = element(by.xpath("(//a[text()='" + dat + "'])[2]"));
}
}
us_dat.click();
browser.sleep(1000);
where dat is a variable, where I have stored the date that needs to be selected in the calendar picker.
During debugging, I found that, when the date is greater than 24, the code is checking the "if" block present under the "else" block. However, it returns a value of undefined and hence it is skipping the action written inside the "if" block. May I know why it is returning a value of "undefined", instead of true or false please?
Please let me know if any further details are required.
Because all Protractor's API is Async and return promise. So isEnabled() is not return Boolean value directly, you can't directly compare it with a boolean value. You should do the comparing in then() or use await.
Another thing, you no need to put xpath into (), like (//a[text()='click me']).
var us_dat = element(by.xpath("//a[text()='" + dat + "'][1]"));
us_dat.isEnabled().then(function(enabled){
if (dat > 24 && enabled=== false) {
return element(by.xpath("//a[text()='" + dat + "'][2]"));
} else {
return us_dat;
}
})
.then(function(ele){
ele.click();
browser.sleep(1000);
});
try to use this method will work
isEnable: function (element) {
return element.isEnabled();
},

How can I unroll callbacks in Coffeescript?

Normally in Javascript I can do something like this:
var step;
determineStep();
function determineStep() {
step = 'A';
asyncCallbackA(function(result)) {
if (result.testForB) performB();
});
}
function performB() {
step = 'B';
asyncCallbackB(function(result)) {
if (result.testForC) performC();
});
}
function performC() {
step = 'C';
...
}
However Coffeescript does not allow named functions that get hoisted so I would have to define a function before calling it. This would result in them being out of order (very confusing). And if any of them have circular dependencies then it is not possible at all.
In Coffeescript I am forced to do:
step = null
determineStep =
step = 'A'
asyncCallbackA (result) ->
if result.testForB
step = 'B'
asyncCallbackB (result) ->
if result.testForC
step = 'C'
asyncCallbackC (result) ->
...
determineStep()
If you have multiple steps this can quickly get out of hand.
Is it possible to implement the Javascript pattern in Cofffeescript? If not, what is the best way to handle this scenario?
I think you're a little confused. When you say:
f = -> ...
the var f is (of course) hoisted to the top of the scope but the f = function() { ... } definition is left where it is. This means that the only order that matters is that you need to define all your functions before you determineStep().
For example, this works just fine:
f = -> g()
g = -> h()
h = -> console.log('h')
f()
In your case:
step = null
determineStep = ->
step = 'A'
asyncCallbackA (result) -> performB() if(result.testForB)
performB = ->
step = 'B'
asyncCallbackB (result) -> performC() if(result.testForC)
performC = ->
step = 'C'
...
determineStep()
should be fine. determineStep can call performB before performB is defined (in source order) because:
The var performB is hoisted.
By the time determineStep executes, the performB = function() { ... } will have been done.
Similarly for the other functions so you don't have to worry about interdependencies amongst your functions.

Closures over not yet defined variables in CoffeeScript

For the following code:
inc = -> value = (value ? 0) + 1
dec = -> value = (value ? 0) - 1
print = -> console.log value ? 0
How can you make this work properly, so inc and dec close upon value instead of creating separate function-local variables, in the way other than explicitly assigning something to value?
In plain Javascript, you would just declare var value at outer scope:
var value;
function inc() { value = (value || 0) + 1; };
function dec() { value = (value || 0) - 1; };
function print() { console.log(value || 0); };
What is CoffeeScript way for exactly the same thing?
In CoffeeScript, the way to introduce a local variable is to assign to the variable in the appropriate scope.
This is simply the way that CoffeeScript was defined and as such is similar to Python or Ruby, which do not require a "variable declaration", except CoffeeScript also allows forward access. A side-effect is that one cannot shadow a lexical variable.
Just as with the placement of var in JavaScript, where this assignment is done (as long as it is in the correct scope) does not affect the scope of the variable.
Given
x = undefined
f = -> x
// JS
var f, x;
x = void 0;
f = function() {
return x;
};
Given
f = -> x
x = undefined
// JS
var f, x;
f = function() {
return x;
};
x = void 0;