Can't Access Destructuring Assignment from Complex Object - coffeescript

Given the input value:
input =
name:'Foo'
id:'d4cbd9ed-fabc-11e6-83e6-307bd8cc75e3'
ref:5
addtData:'d4cbd9ed-fabc-11e6-83e6-307bd8cc75e3'
data:'bar'
When I try to destructure the input via a function like this:
simplify: (input)->
{ name, ref, id } = input
...the return value is still the full input or a copy of the input.
Am I missing something simple here? How can I access the destructured value. If you can't access the value via a return, it seems that destructuring has little value outside of locally scoped values.

While this isn't necessarily an advantage, the only way I was able to transpile and get the correct answer was to assign the destructure values to the local scope using # (aka this).
input =
name:'foo'
data:'bar'
id: 12314
key:'children'
ref:1
f = (input)->
{ #name, #id } = input
r = {}
f.call(r, input)
console.log r # Object {name: "foo", id: 12314}
working example - link
If someone has a better way to approach this, please add an answer so I can select it as this doesn't seem like the best way.

Related

Rescript Record: Key as Array

In Rescript, one can define a Record in this format:
type record1 = {
a : String
}
but NOT:
type record2 = {
[a] : String
}
I am looking to write a record that compiles to JS like:
{
[Op.or]: [12,13]
}
The use case above comes from Sequelize, and the reference is here.
My current solution:
%raw(`{[Op.or]:[12,13]}`)
It's not entirely clear how you intend to interface with the Op construct, whether you can bind to it or not, but here's an example that does, and along with Js.Dict.t effectively produces the same output:
module Op = {
#val external or: string = "Op.or"
}
Js.Dict.fromList(list{
(Op.or, [12, 23])
})
It does not directly compile to the JS you want, however, which might be a problem if you rely on something that actually parses the source code. But short of that, I believe this should do what you ask for.

Dart: How to force string interpolation on a variable

I have a variable that contains a string with interpolated variables. In the code below, that variable is template. When I pass this variable to generateString function, I want to apply string interpolation on it because the values which interpolated variables require are available in generateString function only.
void main() {
String template = '<p>\${name}</p>';
var res = generateString(template);
}
generateString(template) {
var name = 'abc';
print(template);
return template;
}
The problem is when I am printing and returning template inside generateString fn, I am getting <p>${name}</p> instead of <p>abc</p>. Is there a way to explicitly tell the dart to so string interpolation?
I am new to Dart. I don't know if it is even possible to achieve or not. Please suggest how do I do this.
Edit: Based on the inputs from other users, I would like to make a clarification about the scenario presented. The value of template variable is not a string literal. I get that from UI as a user input. I have shown it here as a string literal for code simplicity. Also, please consider that name and template are not in the same scope in my scenario.
The other answers so far are wrong.
String interpolation (looking for $, etc) happens only while compiling from the source code to the value in memory. If that string in turn also has a $, it's no longer special.
It's not possible to trigger interpolation past the original compilation step. You can write a templating system that would look for something like {{name}} in the value, and replace it with the current value of name.
If you have the template and the variable in the same scope, it works as expected.
// evaluate variable inside ${}
var sport = 'basketball';
String template = 'I like <p>${sport}</p>';
print(template);
I didn't fully understand your question maybe this will help
void main() {
print(generateString('abc')); //<p>abc</p>
}
generateString(String template) {
return r"<p>" "$template" r"</p>";
}
Walter White here.
You must define the variable name as global var, so it can "cook" the string for you

Return value is not the same as predicted from a defined function

james=open('C:/Users/skora da_bura/Documents/data.txt')
jake=james.read()
james.close()
numblist=[]
charlist=[]
def Read(numblist,charlist):
for i in range(0,len(jake),4):
numblist.append(int(jake[i]))
for i in range(2,len(jake),4):
charlist.append(jake[i])
Bring = numblist,charlist
james = open('C:/Users/skora da_bura/Documents/data.txt')
jake22 = james.readlines()
james.close()
back='Number of lines read',len(jake22)
return back
print(Read([],[]))
print(charlist)
the charlist returns [] even though I had appended values to it to make a list when I was defining the function Read.
I don't seem to see what the problem is with the code
The charlist you define in the signature of Read shadows the global charlist. They're different variables that happen to have the same name. If you intend to modify the global variable, you shouldn't try to pass it as a parameter.

When does Chapel pass by reference and when by constant?

I am looking for examples of Chapel passing by reference. This example works but it seems like bad form since I am "returning" the input. Does this waste memory? Is there an explicit way to operate on a class?
class PowerPuffGirl {
var secretIngredients: [1..0] string;
}
var bubbles = new PowerPuffGirl();
bubbles.secretIngredients.push_back("sugar");
bubbles.secretIngredients.push_back("spice");
bubbles.secretIngredients.push_back("everything nice");
writeln(bubbles.secretIngredients);
proc kickAss(b: PowerPuffGirl) {
b.secretIngredients.push_back("Chemical X");
return b;
}
bubbles = kickAss(bubbles);
writeln(bubbles.secretIngredients);
And it produces the output
sugar spice everything nice
sugar spice everything nice Chemical X
What is the most efficient way to use a function to modify Bubbles?
Whether Chapel passes an argument by reference or not can be controlled by the argument intent. For example, integers normally pass by value but we can pass one by reference:
proc increment(ref x:int) { // 'ref' here is an argument intent
x += 1;
}
var x:int = 5;
increment(x);
writeln(x); // outputs 6
The way that a type passes when you don't specify an argument is known as the default intent. Chapel passes records, domains, and arrays by reference by default; but of these only arrays are modifiable inside the function. ( Records and domains pass by const ref - meaning they are passed by reference but that the function they are passed to cannot modify them. Arrays pass by ref or const ref depending upon what the function does with them - see array default intent ).
Now, to your question specifically, class instances pass by "value" by default, but Chapel considers the "value" of a class instance to be a pointer. That means that instead of allowing a field (say) to be mutated, passing a class instance by ref just means that it could be replaced with a different class instance. There isn't currently a way to say that a class instance's fields should not be modifiable in the function (other than making them to be explicitly immutable data types).
Given all of that, I don't see any inefficiencies with the code sample you provided in the question. In particular, here:
proc kickAss(b: PowerPuffGirl) {
b.secretIngredients.push_back("Chemical X");
return b;
}
the argument accepting b will receive a copy of the pointer to the instance and the return b will return a copy of that pointer. The contents of the instance (in particular the secretIngredients array) will remain stored where it was and won't be copied in the process.
One more thing:
This example works but it seems like bad form since I am "returning" the input.
As I said, this isn't really a problem for class instances or integers. What about an array?
proc identity(A) {
return A;
}
var A:[1..100] int;
writeln(identity(A));
In this example, the return A in identity() actually does cause a copy of the array to be made. That copy wasn't created when passing the array in to identity(), since the array was passed by with a const ref intent. But, since the function returns something "by value" that was a reference, it's necessary to copy it as part of returning. See also arrays return by value by default in the language evolution document.
In any case, if one wants to return an array by reference, it's possible to do so with the ref or const ref return intent, e.g.:
proc refIdentity(ref arg) ref {
return arg;
}
var B:[1..10] int;
writeln(refIdentity(B));
Now there is no copy of the array and everything is just referring to the same B.
Note though that it's currently possible to write programs that return a reference to a variable that no longer exists. The compiler includes some checking in that area but it's not complete. Hopefully improvements in that area are coming soon.

Correct way to return function value instead of binding in Coffeescript

I can't seem to find a concise answer to this question. What is the correct coffeescriptic way to return the value from _otherInstanceMethod when calling #_instanceMethod instead of the function binding itself?
x = _instanceMethod: () ->
#_otherInstanceMethod key: 'value'
Edit (thanks commenters)
This returns:
x = function () {
[...] # function body omitted
});
Instead of
x = 'some value returned by _otherInstanceMethod'
I would like the value to be returned instead of the function binding to _otherInstanceMethod
Being totally new to Coffeescript, this was my fault. I was calling the instance method like:
#_instanceMethod
instead of
#_instanceMethod()
Sorry for the trouble, voting to delete
In CoffeeScript #something translated into this.something regardless of the underlying variable type. This means you can use # only in conjuction with properties, with methods you still ought to use good old this.