Can I implement operator overrides in typescript? - operator-overloading

Say I am creating a Dictionary class in typescript. Is there a way to have operator overrides so I can define the operator "[string]" instead of having to use the function get(string)?

No, you cannot have operator overloading. JavaScript does not have a notion of this.
You can override toString, though:
class Thing {
toString() {
return 'I am a Thing!';
}
}
var x = new Thing();
console.log('X says ' + x); // Prints "X says I am a Thing!"

Related

Dart Language Extension Method

I am reading extension method in dart official documentation, and reached the bottom of the document. Here, the documentation mentioned the line List<T> operator -() => reversed.toList(); as a extension method on List<T>.
Here is the complete code.
extension MyFancyList<T> on List<T> {
int get doubleLength => length * 2;
List<T> operator -() => reversed.toList();
List<List<T>> split(int at) => [sublist(0, at), sublist(at)];
}
What does mean operator -(), operator +(List<T> t),and operator *(List<T> t) and how can I use these as extension method on List?
It means you can actually use it as an operator on the list. For example:
final list = [1,2,3,4,5];
print(-list);
prints [5,4,3,2,1]
Personally, I would not implement a revers like this. I think it would be quite unclear for other developers, while the reversed method is very clear on what it does. However, I understand it is just an example on how to define an operator in an extension.
operator +(List<T> t) and operator *(List<T> t) is between two lists. For example:
final a = [1,2];
final b = [3,4];
print(a + b);
prints [1,2,3,4]

Extending list pseudo methods in Specman

Is there a way I could extend the given pseudo methods for lists in e, to add some specific implementation?
Thanks
"pseudo method" is not really a method, it just looks as if it was. So it cannot be extended with "is also/only/etc".
but you can define any "pseudo method" of your own, using macro.
for example - pseudo method that adds only even items -
(do note the \ before the () )
define <my_pseudo_method'action> "<input1'exp>.add_if_even\(<input2'num>\)"
as computed {
result = append("if ", <input2'num>, " %2 == 0 then { ", <input1'exp>, ".add(", <input2'num>, ")};");
}
then can be called from another file -
extend sys {
run() is also {
var my_list : list of int;
for i from 0 to 10 {
my_list.add_if_even(i);
};
print my_list;
};
};
Using a macro, you can even "override" an existing pseudo-method. For example, let's say you want to modify add() so that it will add an element to the list only if it is not already in the list. (In other words, you want to keep all elements in the list unique).
You can do something like this:
define <my_add'action> "<list'exp>.add\(<exp>\)" as {
if not <list'exp>.has(it == <exp>) then {
var new_size<?>: int = <list'exp>.size() + 1;
<list'exp>.resize(new_size<?>, TRUE, <exp>, TRUE);
};
};
Note that I use another pseudo-method here - resize() - to implement the actual addition of the new element to the list. If I tried to use the add() pseudo-method itself, it wouldn't work, and would lead to an infinite recursion. This is because add() used inside the macro would again call the macro itself, and not the pre-defined pseudo-method being overridden.
You can also use templates to add/modify list pseudo-methods. e.g.
<'
template struct MyList of (<T1'type>) {
items: list of <T1'type>;
keep soft items.size()==10;
pop_index(i:int):<T1'type> is {
result = items[i];
items.delete(i);
};
};
extend sys {
list1: MyList of (byte);
// somehwere
var foo:= list1.pop_index(3);
};
'>

Implementing TypeScript interface with bare function signature plus other fields

How do I write a class that implements this TypeScript interface (and keeps the TypeScript compiler happy):
interface MyInterface {
(): string;
text2(content: string);
}
I saw this related answer:
How to make a class implement a call signature in Typescript?
But that only works if the interface only has the bare function signature. It doesn't work if you have additional members (such as function text2) to be implemented.
A class cannot implement everything that is available in a typescript interface. Two prime examples are callable signatures and index operations e.g. : Implement an indexible interface
The reason is that an interface is primarily designed to describe anything that JavaScript objects can do. Therefore it needs to be really robust. A TypeScript class however is designed to represent specifically the prototype inheritance in a more OO conventional / easy to understand / easy to type way.
You can still create an object that follows that interface:
interface MyInterface {
(): string;
text2(content: string);
}
var MyType = ((): MyInterface=>{
var x:any = function():string { // Notice the any
return "Some string"; // Dummy implementation
}
x.text2 = function(content:string){
console.log(content); // Dummy implementation
}
return x;
}
);
There's an easy and type-safe way to do this with ES6's Object.assign:
const foo: MyInterface = Object.assign(
// Callable signature implementation
() => 'hi',
{
// Additional properties
text2(content) { /* ... */ }
}
)
Intersection types, which I don't think were available in TypeScript when this question was originally asked and answered, are the secret sauce to getting the typing right.
Here's an elaboration on the accepted answer.
As far as I know, the only way to implement a call-signature is to use a function/method. To implement the remaining members, just define them on this function. This might seem strange to developers coming from C# or Java, but I think it's normal in JavaScript.
In JavaScript, this would be simple because you can just define the function and then add the members. However, TypeScript's type system doesn't allow this because, in this example, Function doesn't define a text2 member.
So to achieve the result you want, you need to bypass the type system while you define the members on the function, and then you can cast the result to the interface type:
//A closure is used here to encapsulate the temporary untyped variable, "result".
var implementation = (() => {
//"any" type specified to bypass type system for next statement.
//Defines the implementation of the call signature.
var result: any = () => "Hello";
//Defines the implementation of the other member.
result.text2 = (content: string) => { };
//Converts the temporary variable to the interface type.
return <MyInterface>result;
})(); //Invokes the closure to produce the implementation
Note that you don't need to use a closure. You could just declare your temporary variable in the same scope as the resulting interface implementation. Another option is to name the closure function to improve readability.
Here's what I think is a more realistic example:
interface TextRetriever {
(): string;
Replace(text: string);
}
function makeInMemoryTextRetriever(initialText: string) {
var currentText = initialText;
var instance: any = () => currentText;
instance.Replace = (newText: string) => currentText = newText;
return <TextRetriever>instance;
}
var inMemoryTextRetriever = makeInMemoryTextRetriever("Hello");

overload operator = in c#

Is it possible to overload operator = in c#?
when i call =, i just want to copy properties, rather than making the left hand reference to refer another instance.
The answer is no:
Note that the assignment operator itself (=) cannot be overloaded. An assignment always performs a simple bit-wise copy of a value into a variable.
And even if it was possible, I wouldn't recommend it. Nobody who reads the code is going to think that there's ANY possibility that the assignment operator's been overloaded. A method to copy the object will be much clearer.
You can't overload the = operator. Furthermore, what you are trying to do would entirely change the operator's semantics, so in other words is a bad idea.
If you want to provide copy semantics, provide a Clone() method.
Why not make a .CopyProperties(ByVal yourObject As YourObject) method in the object?
Are you using a built-in object?
We can Overload = operator but not directly.
using System;
class Over
{
private int a;
public Over(int a )
{
this.a = a;
}
public int A { get => a; }
public static implicit operator int(Over obj)
{
return obj.A;
}
}
class yo
{
public static void Main()
{
Over over = new Over(10);
int a = over;
}
}
Here when you call that operator overloading method , it is calling = operator itself to convert that to int. You cannot directly overload "=" but this way of code means the same.

Can I define functions outside of a class using MooseX::Declare?

I recently started using the module MooseX::Declare. I love it for its syntax. It's elegant and neat. Has anyone come across cases where you would want to write many functions (some of them big) inside a class and the class definition running into pages? Is there any workaround to make the class definition to just have the functions declared and the real function definition outside the class?
What I am look for is something like this -
class BankAccount {
has 'balance' => ( isa => 'Num', is => 'rw', default => 0 );
# Functions Declaration.
method deposit(Num $amount);
method withdraw(Num $amount);
}
# Function Definition.
method BankAccount::deposit (Num $amount) {
$self->balance( $self->balance + $amount );
}
method BankAccount::withdraw (Num $amount) {
my $current_balance = $self->balance();
( $current_balance >= $amount )
|| confess "Account overdrawn";
$self->balance( $current_balance - $amount );
}
I can see that there is a way to make the class mutable. Does anyone know how to do it?
Easy (but needs adding to the doc).
class BankAccount is mutable {
}
As an aside, why are you defining your methods outside the class?
You can just go
class BankAccount is mutable {
method foo (Int $bar) {
# do stuff
}
}
I want my class definition to be short, and to give an abstract idea of what the class is for. I like the way its been done in C++ where you have an option to define functions inline or outside the class using the scope resolution operator. This makes the class definition short and neat. This is what I am looking for.
Thanks for your time.