Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sunday, March 5, 2023

JavaScript infinite streams

This post was heavily inspired by this post: Infinite Data structures in Javascript  (author: Dimitris Papadimitriou)

After reading the article, I also wanted to have the bare minimum, and most simple implementation of a Stream - and surprisingly, it is very easy (in terms of code), but also, kinda complicated. Kind of the sweetspot I really like to learn about!

In this implementation, we add a filter method to the stream object, which takes a predicate function pred and returns a new stream object with only the elements that pass the predicate. If the current value passes the predicate, then the resulting stream will include the current value and the result of calling filter on the next property. Otherwise, the resulting stream will only include the result of calling filter on the next property. If there is no next property, then the emptyStream object is returned.

The resulting mappedStream is a stream of strings with the same structure as the original stream, but with each element converted to a string. The resulting filteredStream is a stream with only the elements that are greater than 1.


Thursday, September 15, 2022

Jest test array with objects without order

Hello internet!

As I was doing my regular weekday I met a surprisingly unsolved problem in Jest, namely what if I wanted to test an array's _content without order_?

So e.g. these 2 arrays should equal

[{cat: 'Takira'}, {cat: 'Inari'}]

and

[{cat: 'Inari'}, {cat: 'Takira'}].

There is an SO post about this, but it doesn't care about objects, but only primitives. Also it points to Jasmine (which does have this as a native feature), but not Jest.

So here is my generic solution to the problem

for (obj in array) {

    expect(obj).toEqual(

        expect.arrayContaining([

            expect.objectContaining(obj)

        ])

    );

}

Let's go through this step by step!

So we are looping through the array (so far so good) and then we simply expect that object to be in the array.

That's literally it.

Thank You For Coming to My TED Talk.

Saturday, April 10, 2021

Conditional Promise.all

Have been in a situation where you needed to dynamically shoot out HTTP requests based on some branching logic? Are you using a Promise based HTTP client library like fetch or axios?

Fear not, here is a solution for your needs!

In general the solution is based on coming up with an interface that's not only returning the data when the Promise was resolved, but also give a companion flag that identifies the promise it was initiated from.


You can find the idea on this SO post as well.

Wednesday, November 20, 2019

My bookmarks as of 20.11.2019

I would like to share all of my Computer Science related bookmarks I added so far (as of 20.11.2019).
I edited a folder visualization tool (link in the pen), so you can also easily just export your JSON bookmarks from e.g. Chrome and give it a go in this visualization.
Hint: it's searchable!

Wednesday, September 28, 2016

Game of life with every pixel on a canvas!

Hello everyone!

Long time haven't posted, so here is a new dirty marble of mine: game of life using every pixel on a canvas!
My first thought was: "this is brilliant!", but eventually it turned out it is eating a lot of memory. - But still, it was worth the 2 hours I spent with!

You can learn more about the "game of life" here: https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life .


Friday, June 10, 2016

JavaScript and AngularJS basics

This week I had a presentation in Frankfurt for my LH Systems colleagues about JS and Angular in general.
I really had fun over there since they were such a nice audience. Thanks guys!
Here are the links for the presentations:

Sunday, March 1, 2015

OOP in JavaScript

If you are creating a big project, you are going to have problems with the maintenance of your code. It is a common solution to this problem to use OOP methodology. Fortunately, JavaScript gives you the tool to be able to use these concepts.
There are lots of ways to do this, I am going to cover two big techniques to reach your goal: to be OO. First, you have to understand the basic concepts behind the prototypical behaviour of JavaScript.

Prototypal inheritance (object literal)

Let's look at this example
var parent = {
    get: function fn(){
        return this.val;
    },
    val:42
};

var child = Object.create(parent);
child.val = 69;
var grandchild = Object.create(child);

parent.get(); //42
child.get(); //69
grandchild.get(); //69

E.g. what happens at the child.get(); call? The value attribute is set to 69. That's clear. But what will be it's get function? Here comes the cool part. Obviously the child object does not implement any get functions, so the JavaScript engine will seek for it in the prototype chain. It will go back to it's prototype object (an dif there is no implementation of get, it will look at it's prototype, etc.. That's what we call 'prototype chain'.), and call it's get function, however the this keyword is going to reference to the child object. Pretty neat, isn't it?
For more information about Object's create function check out this link.
An important note: polymorphism is also available in JavaScript (just like in e.g. JAVA):
var greatgrandchild = Object.create(grandchild);
greatgrandchild.get = function() {
    return this.val + " is my val."

};
greatgrandchild.get(); //"69 is my val."
Also we can create a contructor in an object:
var MyObject = {
    constructor: function(value) {
        this._val = value;
    },
    get: function() {
        return this._val;
    }
};

MyObject.constructor(42);
MyObject.get(); //42 

Functional inheritance (the "classical" model)

This model is very similar to what we learned before. It has constructor as well, but this time it will point back to the function. So basically the function we create will be the constructor of our class. We can do this by calling the keyword new.
var XXX = function() {
    console.log("Here I am, sitting on a tree.");
};
XXX.prototype.constructor; //function () {console.log("Here I am, sitting on a tree.");}
var x = new XXX(); //"Here I am, sitting on a tree."

So every time we create a function, two objects are created: the function object and the prototype object, who holds a constructor variable, who is pointing back to the function object. A bit weird.
As we see, every function is a contructor in it's own way, however, not every function was meant to be a class.
So how can we do inheritance with this model?
It is very similar to the previous object notation inheritance, but this time we have to give explicitly a value to the object's prototype variable, like the following.

//class Animal
var Animal = function(_feet) {
    this.feet = _feet;
};
Animal.prototype.eat = function() {
    console.log("I am eating, omnomnom..");
};
Animal.prototype.info = function() {
    console.log("I have this amount of feet: " + this.feet);
};

//class Cat extends Animal
var Cat = function(_feet, _miceHaveEaten) {
    Animal.call(this, _feet);
    this.miceHaveEaten = _miceHaveEaten;
    var privateVariable = "This is not available outside the class!";
};
Cat.prototype = new Animal();
Cat.prototype.purr = function() {
    console.log("Purrrrrr.........");
};
//polymorphism
Cat.prototype.info = function() {
    console.log("I have eaten this amount of mice so far: " + this.miceHaveEaten + ", also I have " + this.feet + " feet.");
};

var unicellular = new Animal(0);
unicellular.eat();
unicellular.info();

var cico = new Cat(4, 9001);
cico.eat();
cico.purr();
cico.info();

Important note: if we declare a e.g. function in a class with the keyword this, it is going to be assigned to every instance of the class. Typically we don't want to do this, so we want to assign it only to the class's prototype.
Important note #2: we can declare private variables inside a class as you can see in the declaration of the class Cat. This can be done by easily using the var keyword, not using the reference to the object with the this keyword.
Not so important, but very interesting note: you cant change the value of this with the '=' operator. If you want to do a call like the following: this="this"; , the browser will give a ReferenceError: Invalid left-hand side in assignment. error.
I highly recommend you to try all these code snippets in your browser's console for example to get a more in depth understanding of these concepts.

Exercise

Create a class called "Orc" using the classical model. It has an "ugliness" property which is set in the constructor. This property is a Number between 0 and 100, the default value is 100. This class has a method called "intimidate", which writes to the console "You will fear me cuz my ugliness index is: " plus the object's "ugliness" property.
Create a subclass "UrukHai" which inherits from the class "Orc". It has one other property than "Orc"'s, this is called "strongness", a Number between 0 and 10, the default value is 0. It has a new method called "attack", which writes to the console: "I will crush you cuz my ugliness index is {{ugliness}}, and my strongness is: {{strongness}}".
Also create some instances of the classes showing all the methods of a class.

//class Orc
var Orc = function(_ugliness) {
    if (_ugliness > 0 && _ugliness < 100) {
        this.ugliness = _ugliness;
    } else {
        this.ugliness = 100;
    }
};
Orc.prototype.intimidate = function() {
    console.log("You will fear me cuz my ugliness index is: " + this.ugliness);
};

//class UrukHai extends Orc
var UrukHai = function(_ugliness, _strongness) {
    Orc.call(this, _ugliness);
    if (_strongness > 0 && _strongness < 10) {
        this.strongness = _strongness;
    } else {
        this.strongness = 0;
    }
};
UrukHai.prototype = new Orc();
UrukHai.prototype.attack = function() {
    console.log("I will crush you cuz my ugliness index is " + this.ugliness + ", and my strongness is: " + this.strongness);
};

Monday, February 23, 2015

JavaScript difference between bind() VS call() and apply()

First of all let me discuss about the keyword this in JavaScript.
this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. So e.g. create an object called obj like this:
var obj = {
    x: 81,
    getX: function() {
        console.log(this.x);
        return this.x;
    }
};
obj.getX(); //81
Here the this keyword refers to the object (obj) itself because we are going to call this function from the object's context. A golden rule here is to look at who called the function. Another example could be a global function:
function globalFunction() {
    console.log(this);
}
This can be confusing, because a man could think 'so who is calling this function? Who is the owner?
Well, JavaScript has a bad habit of dealing with variables: the function will be assigned to the global variable, in a browser it is the window object. So right now these two calls are equivalent:
globalFunction();
window.globalFunction();
Therefore in the function globalFunction, this will refer to the global window object.
Now let's move on to the next step to understand the functions bind, call and apply.
With these functions we can manipulate the keyword this in a function. Very interesting, and indeed, we do need these kind of functions. Why? E.g. jQuery's forEach call on a set of HTML elements would be very funny to use if the keyword this would not be the element of the iteration, isn't it? So the implementation includes the the function call to make sure, this is referred to the variable of the iteration.
But let's take a look back to our example. How can we force obj 's getX function to reference the this keyword to a variable we want to give? The solution is what (hopefully) you think: call, apply and bind functions. Let's see on examples, what is happening with each cases:
var otherObj = {
    x: 99
};
obj.getX.call(otherObj); //99
obj.getX.apply(otherObj); //99
var myGetXFunction = obj.getX.bind(otherObj); //returns a function
myGetXFunction(); //99
What is happening here? call will manipulate the this keyword to our variable in the first argument inside the function. The only difference between call and apply is apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.
However, bind will not execute the function. bind will only give a reference to a function, which is similar to the original function, but the keyword this is changed to our variable. Very elegant!
I hope you understand now more the meaning and reason behind these functions.
A JSFiddle example is below:

Wednesday, August 28, 2013

JAVA & JavaScript String, Integer, etc.. what does "=" operator?

So today I got a very interesting problem in a JSP project, a discussion about it is here:
http://www.coderanch.com/t/618736/JSP/java/Object-scope-page-including-JSP

So Idecided to make some very simple but enlightetning examples in JAVA and JavaScript:
JAVA:
import java.util.*;

public class Adam {
 public static void main(String[] args){
  String adam = "adam";
  Integer notPrimitiveInteger = 10;
  int primitiveInteger = 20;
  ArrayList arrList = new ArrayList();
  arrList.add(1);
  arrList.add(2);
  doSomething(adam,notPrimitiveInteger,primitiveInteger,arrList);
  System.out.println(adam);
  System.out.println(notPrimitiveInteger);
  System.out.println(primitiveInteger);
  System.out.println(arrList.size());
 }
 private static void doSomething(String adam,Integer notPrimitiveInteger,int primitiveInteger,ArrayList arrList){
  adam = "notAdam";
  notPrimitiveInteger = 500;
  primitiveInteger = 7000;
  arrList.add(3);
 }
}
//Ignore this line :)
And the output is:
adam
10
20
3
 So what is happening?
Basically every time you are making expression's like this:
blabla = "blabla";

every time it's like a  new object is created (in fact not!, but broadly that's the case, learn more here). So it's like you are using the new String(".."); expression, but it's not showed. So when you're about to pass a String or an Integer object to a function , you could get the value of it, but if you want to change it, it will be not changed, because the "=" expression is like making a new object. Again: not making new object, but it behaves like it is.
And what about the ArrayList?
The ArrayList's add(..) function does not make a new ArrayList object! It's like you're working with it's reference, so the original ArrayList object will be changed!
JavaScript:
 var adam = new String("adam");
 var integ = 10;
 var arr = new Array();
 arr.push(1);
 arr.push(2);
 arr.push(3);
 var obj = new Object();
 obj.adam = "oldValue";
 console.log(arr);
 doSomething(adam,integ,arr,obj);
 function doSomething(adam,inte,arr,obj){
  adam="notadam";
  inte="500";
  arr.pop();
  obj.adam="newValue";
 }
 console.log(adam);
 console.log(integ);
 console.log(arr);
 console.log(obj);
And the output is:
The solution is the same as JAVA's.