I saw a class A, after its class definition
class A
constructor: (#x=0, #y=0) ->
#A = A
what does #A = A here?
It helps to look at the generated output.
// Generated by CoffeeScript 1.9.3
(function() {
var A;
A = (function() {
function A(x, y) {
this.x = x != null ? x : 0;
this.y = y != null ? y : 0;
}
return A;
})();
this.A = A;
}).call(this);
So #A translates to this.A. When this is used at the top level, it refers to window. So #A = A exports the A class onto the window object.
This is normally done to export a library. For example, window.$ = jQuery or window._ = lodash.
Related
I want to do something like this in dart.
var z = +
and then put it in another var like this
var x = 5 z 5
And when I did this
var z = +
I get an Error
Expected an identifier.
you can not make variable operators in dart though what you can do is to create a custom variable for the same by doing:
void main() {
var operators = {
'+': (a, b) { return a + b; },
'<': (a, b) { return a < b; },
// ...
};
var op = '+';
var x = operators[op]!(10, 20);
print(x);
}
In lit/lit-html/lit-element, a standard component is the TemplateResult (usually HTMLTemplateResult), created like:
function renderMe(msg) {
return html`<div>Hello ${msg}!</div>`;
}
and of course the power and efficiency of the library is that subsequent calls will reuse the same <div> Element and only replace the changed fragments.
For testing the renderMe() function above, however, it would be helpful to be able to see the return value as a standard string, like:
assert.equal(RENDER_AS_STRING(renderMe('kimiko')), '<div>Hello kimiko!</div>');
and fix any bugs in the function before testing how it renders into the browser itself.
Is there a function like RENDER_AS_STRING either in lit itself or in a testing library? I have searched and not found one.
The result of execution contains html strings and values that alternate:
We can combine them in the same order:
function renderMe(msg) {
return html`<div>Hello ${msg}!</div>`;
}
const getRenderString = (data) => {
const {strings, values} = data;
const v = [...values, ''] // + last emtpty part
return strings.reduce((acc,s, i) => acc + s + v[i], '')
}
console.log(getRenderString(renderMe('SO')))
You can test it in the playground
And the recursive version
import {html, css, LitElement} from 'lit';
function renderMe(msg) {
return html`<p>Hello ${msg}!</p>`;
}
function renderBlock(msg) {
return html`<div>${renderMe(msg)}</div>`;
}
const getRenderString = (data) => {
const {strings, values} = data;
const v = [...values, ''].map(e => typeof e === 'object' ? getRenderString(e) : e )
return strings.reduce((acc,s, i) => acc + s + v[i], '')
}
document.getElementById('output').textContent = getRenderString(renderBlock('SO'))
#Daniil Loban's answer works great if the arguments are strings, but if they might themselves be TemplateResults or arrays of TemplateResults (which are all allowed by spec), it needs a more complex answer:
export function template_as_string(data) {
const {strings, values} = data;
const value_list = [...values, '']; // + last empty part
let output = '';
for (let i = 0; i < strings.length; i++) {
let v = value_list[i];
if (v._$litType$ !== undefined) {
v = template_as_string(v); // embedded Template
} else if (v instanceof Array) {
// array of strings or templates.
let new_v = '';
for (const inner_v of [...v]) {
new_v += template_as_string(inner_v);
}
v = new_v;
}
output += strings[i] + v;
}
return output;
}
Code
void main() {
int printit(var y, var z){
var c = y+10;
print (y);
return c;
}
printit(20,23);
var b = printit(1,3);
print (b);
}
Why does the above code in DartPad gives output as this?
20
1
11
Output
Why does it prints the function for the second time when I am trying to add the return value of the function to a variable 'b'?
It prints it because you call print(b) in the following line.
Remove the line and the output should be as below:
20
1
Try using the code snippet below
void main() {
int printit(var y, var z){
var c = y+10;
return c;
}
var b;
b= printit(20,23);
print (b);
b = printit(1,3);
print (b);
}
It prints 1 because you assigned to b the value printit(1,3) and in your function itself you ask for printing y (here 1) with print(y).
void main() {
int printit(var y, var z){
var c = y+10;
print (y); // this line is responsible for printing 1. Try removing this.
return c;
}
printit(20,23);
var b = printit(1,3);
print (b);
}
I have a struct like so:
struct tTest{
char foo [1+1];
char bar [64];
};
In TypesScript I have
export interface tTest{
foo: string;
bar: string;
}
Is there a way to add [64] and [1+1] to the type?
As the comments say: js/ts don't support the char type and there's no way to declare array/string lengths.
You can enforce that using a setter though:
interface tTest {
foo: string;
}
class tTestImplementation implements tTest {
private _foo: string;
get foo(): string {
return this._foo;
}
set foo(value: string) {
this._foo = value;
while (this._foo.length < 64) {
this._foo += " ";
}
}
}
(code in playground)
You'll need to have an actual class as the interfaces lacks implementation and doesn't survive the compilation process.
I just added spaces to get to the exact length, but you can change that to fit your needs.
You can't force the length of an array in Typescript, as you can't in javascript.
Let's say we have a class tTest as following:
class tTest{
foo = new Array<string>(2);
};
As you can see, we have defined an array of string with length 2, with this syntax we can restrict the type of values we can put inside our array:
let t = new tTest();
console.log('lenght before initialization' + t.foo.length);
for(var i = 0; i < t.foo.length; i++){
console.log(t.foo[i]);
}
t.foo[0] = 'p';
t.foo[1] = 'q';
//t.foo[2] = 3; // you can't do this
t.foo[2] = '3'; // but you can do this
console.log('length after initialization' + t.foo.length);
for(var i = 0; i < t.foo.length; i++){
console.log(t.foo[i]);
}
In this manner we can't put a number value inside your array, but we can't limit the number of values you can put inside.
Playground
I want to add the ability to extend javascript objects by adding a method to the prototype.
The method will receive one or more other objects and will add all of the key/values to this.
This is what I came up with:
Object::extend = (objects...) ->
#[key] = value for key, value of object for object in objects
or this:
Object::extend = (objects...) ->
for object in objects
for key, value of object
#[key] = value
Both work as expected, and compile into the same javascript code:
var __slice = [].slice;
Object.prototype.extend = function() {
var key, object, objects, value, _i, _len, _results;
objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
_results = [];
for (_i = 0, _len = objects.length; _i < _len; _i++) {
object = objects[_i];
_results.push((function() {
var _results1;
_results1 = [];
for (key in object) {
value = object[key];
_results1.push(this[key] = value);
}
return _results1;
}).call(this));
}
return _results;
};
What I'm not too happy about is the whole results thing that is created per for loop which is completely redundant for my purpose.
Is there a way to get a code more like:
Object.prototype.extend = function() {
var key, object, objects, value, _i, _len;
objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
for (_i = 0, _len = objects.length; _i < _len; _i++) {
object = objects[_i];
(function() {
for (key in object) {
value = object[key];
this[key] = value;
}
}).call(this);
}
};
Thanks.
Edit
I'm aware that I can simply embed javascript code, but looking for a coffeescript solution.
You can try adding an explicit return:
Object::extend = (objects...) ->
for object in objects
for key, value of object
#[key] = value
return
That produces this:
var __slice = [].slice;
Object.prototype.extend = function() {
var key, object, objects, value, _i, _len;
objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
for (_i = 0, _len = objects.length; _i < _len; _i++) {
object = objects[_i];
for (key in object) {
value = object[key];
this[key] = value;
}
}
};
Every CoffeeScript function returns the value of the last expression in the function, CoffeeScript loops are also expressions. That means that CoffeeScript has to build all that _results stuff to produce a return value for your function since you had an implicit return applying to the outer loop. If you remove that implicit return by adding an explicit "return nothing" then the CS→JS compiler seems to be smart enough to not do all that extra _results work.