return multiple functions in Dart - javascript

I want to return various functions as the javascript object.
payments(auth_user).create();
payments(auth_user).delete(1);
to do this in javascript, look like this:
function payments(auth_user) {
return {
delete(id) {
//
}
}
}
But in Dart... How to do it?

The Dart way is to create a class that implements .create and .delete, and have payments return an instance of that class. There are no "anonymous classes" in Dart, as you can pretend in JavaScript.

Related

What is a way to implement a scala `Either[A,B]` structure in Koa / Javascript

I have a few projects with Play scala and I have found it quite useful to use the scala Either[A, B] construct in the models so that in my controller I have something like (as an example)
val modelResult:Either[String, String] = ...
modelResult match {
case Left(a) => Ok(... do something here that is meant for a 200 ....)
case Right(err) => BadRequest(display an error in a 400)
}
what would be a good way to do something similar in Javascript (I use the Koa framework)
For those who are not familiar with the Either construct
https://www.scala-lang.org/api/2.12.0/scala/util/Either.html
Have a look at one of the many FP libraries for JavaScript. Rambda is a popular one (see docs/#either). You may also have a look at daggy for modelling co-products.
Thinking in Rambda provides a good introduction to Rambda
How about something like this?
class Either {}
class Left extends Either {
constructor(leftValue) {
super()
this.leftValue = leftValue;
}
match(lHandler, unused) {
return lHandler(this.leftValue);
}
}
class Right extends Either {
constructor(rightValue) {
super()
this.rightValue = rightValue;
}
match(unused, rHandler) {
return rHandler(this.rightValue);
}
}
Usage:
const either = ... // e.g. new Left('Test');
either.match(
left => console.log(left),
right => console.warn('An error occurred'),
);
To make this really useful, I suggest adding map, flatMap, etc.

Creating generic classes and functions in javascript ES06

I'm from java background. I use Generics in java in following way:
class ApiResponse<T> {
T data;
T getData(){
return T;
}
}
I'm unable to use generics in javascript ES06. I wanna know whether it's possible or not creating generic classes?
JavaScript is a dynamically typed language and it doesn't have any generics. You can write a normal function/method, it will work for all types.
P.S. Use Typescript if want to code like you do in Java.
How do you like this, Elon Musk? Pure js, no typeflow/typescript
class BaseClass {
hello = function () {
console.log('hello!');
}
}
function GenericClass(T, Base) {
return class extends Base {
field = new T();
}
}
class DerivedFromGeneric extends GenericClass(String, BaseClass) {
greet = function() {
this.hello();
console.log('greetings ', this.field);
}
}
let i = new DerivedFromGeneric();
Javascript in itself doesn't provide any syntax to support generic classes. But it's possible using:
Flow
or
Typescript
Let me show an example of using generic class using Flow in javascript ES06:
export class ApiResponse<T> {
data: ?T = null
}
You can use Typescript for this purpose.
https://www.typescriptlang.org/docs/handbook/generics.html
Javascript doesn't have strict typing so there is no need for Generics because all variables can be assigned to any type at any time.

Javascript from Module to Class

I have a javascript module which looks like this:
var myModule = {
settings: {
myage: 25
},
init: function() {
//init code here
},
someFunction1: function(param1) {
//function code here
},
someFunction2: function() {
myModule.someFunction1(myparam);
}
}
I like the structure of modules because it can keep related functions together.
My question is...
Is it bad coding practice to use modules and not classes?
How can I convert the code above to a class? Would it be very hard?
Is is bad coding practice to use modules and not classes?
No!
At least if your module is immutable. If you are dynamically modifying it, you essentially have introduced global state, and that is a bad practise. Also I'm not sure whether these "settings" are supposed to be global or not - if there is any reason (and be it for testing only) to have multiple module instances with different settings, then a class would be appropriate.
How can I convert the code above to a class? Would it be very hard?
Don't when you don't need to. But no, it wouldn't be very hard:
class MyModule {
constructor() {
this.settings: {
myage: 25
};
//init code here
}
someFunction1(param1) {
//function code here
}
someFunction2() {
this.someFunction1(myparam);
}
}
Instead of doing myModule.init(), you'd call var myModule = new MyModule();.

How to protect functions which are called with different contexts from breaking?

I'm fairly new to javascript and now I learned how calling functions with a context works.
Here is a simple example that poses a question in my head. Lets say we have this example:
var myObj = {
bar: function() {
console.log("Lets got to the bar!");
}
}
/* how can this be protected from errors,
* if a passed object doesn't contain bar */
function foo()
{
this.bar();
}
foo.call(myObj);
Now, how can foo be protected of breaking? In some OOP language (lets say Java) this would be implemented lets say via an interface. So in that case if the object being instantiated hasn't implemented the interface method, the compiler would through an error so the compiler protects the code/program from being faulty (in this case of course).
public interface MyInterface
{
public void bar();
}
public class MyClass implements MyInterface
{
public void bar()
{
System.println("Lets go to the bar");
}
}
MyInterface m = new MyClass();
m.bar(); // if bar isn't implemented the compiler would warn/break
Note: I'm not that good in Java so sorry for any syntax or other errors, but I hope you get the point.
So to sum up, as I see that in both cases in both languages one can achieve polymorphism, right? Now if so for the Javascript example, how can one protect it from breaking, are there any patterns or tricks? Does typeof this.bar === function work? If so, who guarantees the SW quality if the programmer forgets this, I'm asking this kind of question because Java has the compiler to warn the programmer about the mistake, does JS have something similar, some quality check tool?
Javascript is a dynamic interpeted* language. There isn't a compiler step to check references. Some tools (jsline) and IDEs (VS, Webstorm) can perform some design-time checks for you, but there's no true type safety. This is largely seen as a feature, not a bug.
There's an array of tricks to work around this (.hasOwnProperty, typeof x === 'function', storing self references, context binding) but mostly, if you want a type safety, you want a different language.
My recommendation is Typescript. It has a Java/C-like syntax, with some familiar OOP features, like classes, interface (and thus, sane polymorphism) and generic types, and transpiles to javascript in moments.
If you use a constructor to create your object you can use Javascript's builtin class member ship checking features. An example is below.
class MyClass {
bar() { console.log("Lets got to the bar!")}
}
function foo() {
if ( this instanceof MyClass ) {
this.bar();
}
else {
console.log('this is not a member of the MyClass');
}
}
foo.call(new MyClass);
Be warned that Javascript's type checking is horribly unreliable and you probably should not use it. If your object contains the same prototype anywhere in it's prototype chain as the class you are testing it for membership in, instanceof will return true.
Quick and dirty duck typing example
This will throw if you give it an object without the properties you are checking for, but you get the idea.
class MyClass {
constructor() {
this.feathers = 'white';
this.feet = 'webbed';
}
bar() { console.log("Lets got to the bar!")}
}
function foo() {
if (
this.hasOwnProperty('feathers') &&
this.hasOwnProperty('feet') &&
this.feathers === 'white' &&
this.feet === 'webbed'
)
{
this.bar();
}
else {
console.log('this is not a member of the MyClass');
}
}
foo.call(new MyClass);

Generics in Typescript - Undefined T

Having a problem with Typescript's Generics where the type is undefined in the scope of the generic function or class. I can't find any documentation on this though I would assume it is by design. Is there a way to achieve what I am trying to, type-safely?
function test<T>() {
return new T();
}
class TestClass<T> {
public build(): T {
return new T();
}
}
Link to Play:
http://www.typescriptlang.org/Playground/#src=function%20test%3CT%3E()%20%7B%0A%09return%20new%20T()%3B%0A%7D%0A%0Aclass%20TestClass%3CT%3E%20%7B%0A%09public%20build()%3A%20T%20%7B%0A%09%09return%20new%20T()%3B%0A%09%7D%0A%7D%0A
TypeScript generics (unlike other languages like C#) are compile time only. So you cannot use them in runtime positions e.g. new T.
Is there a way to achieve what I am trying to, type-safely
Pass the constructor explicitly. e.g.
class TestClass<T> {
public build(x:{new ():T}): T {
return new x();
}
}
Here x:{new ():T} I am saying that x is something that when called with new gives an instance of T.

Categories

Resources