javascript

Bun

Node Js

  • Node team is klein team en onbetaald
  • Voortgang Node versies gaat vooral over niet te veel breaken met voorgaande versies
  • Hierdoor blijven kritisch perfomance issues liggen
  • Gebouwd op de V8 engine. Kijk bv naar de code van de shell

Bun

  • Het Bun team zet in op performance
  • Heeft links met React en Vue
  • Probeert het hele eco systeem van Node te kunnen draaien
  • Kort gezegd een snellere Node

Klachten over Node

  • single threaded & concurrency
  • callbacks
  • Loops
  • Limited standard Libs
  • CPU perfomant tasks & Memory consumption
  • debugging
  • gemopper over update cycle en deprecations

Bun Safari Engine

Safari engine voordelen:
- batterij
- performance webkit
- security
- CJS and ES6 and beyond support
- cross-platform
- kleiner en sneller
- voor de browser

Safari


Wat is Bun nou?

het staat op : Bun Home Page Op Youtube zeggen ze zelf: - Bun is still under development. - Use it to speed up your development workflows or run simpler production code in resource-constrained environments like serverless functions.

- We're working on more complete Node.js compatibility and integration with existing frameworks.

Wat Bun is nou

  • Bun is an all-in-one toolkit for JavaScript and TypeScript apps. It ships as a single executable called bun​.
  • At its core is the Bun runtime, a fast JavaScript runtime designed as a drop-in replacement for Node.js.
  • It's written in Zig and powered by JavaScriptCore under the hood, dramatically reducing startup times and memory usage.
  • Werkt (nog) niet op Windows

Bun Install

Op Linux achtige machines:

# with install script (recommended)  
curl -fsSL https://bun.sh/install | bash  

# with npm  
npm install -g bun  

# with Homebrew  
brew tap oven-sh/bun  
brew install bun  

# with Docker  
docker pull oven/bun  
docker run --rm --init --ulimit memlock=-1:-1 oven/bun  

bun init

Na de check of bun t doet:

bun --version  

Kan je:

bun init

Bun commands

Net zoals npm

upgrade

bun upgrade    

To install dependencies:

bun install
bun i

bun start inhoud folder

branche 01_init na

bun init

bevat de folder

.gitignore
README.md
bun.lockb
index.ts
node_modules
package.json
tsconfig.json


Bun run

hierna klaar voor:

bun run index.ts    

Bun imports

branche 02_say_hello

import van andere ts file


Bun serve

branch 03_bun_serve

start een server op zoals in bv express


Bun scripts

branch 04 bun run start

"scripts": {  
  "start": "bun run index.ts"  
},

Bun Scripts 2

{  
  // ... other fields  
  "scripts": {  
    "clean": "rm -rf dist && echo 'Done.'",  
    "dev": "bun server.ts"  
  }  
}  

bun run clean  
bun run dev  

Bun tsconfig

branch 5 dom en tsconfig

rare errors van mn lsp kon ik oplossen met:

/// <reference lib="dom" />  
/// <reference lib="dom.iterable" />

Bun run

bun run index.ts    

To run a file in watch mode, use the --watch flag.

bun --watch run index.tsx  

Scripts

{  
  // ... other fields  
  "scripts": {  
    "clean": "rm -rf dist && echo 'Done.'",  
    "dev": "bun server.ts"  
  }  
}  

bun run clean  
bun run dev  

Bun test

Bun pagina Run tests

bun test  

Tests are written in JavaScript or TypeScript with a Jest-like API. Refer to Writing tests for full documentation.


Bun test 2

The runner recursively searches the working directory for files that match the following patterns:

  • *.test.{js|jsx|ts|tsx}
    *_test.{js|jsx|ts|tsx}
  • *.spec.{js|jsx|ts|tsx}
  • *_spec.{js|jsx|ts|tsx}

You can filter the set of test files to run by passing additional positional arguments to bun test.


Test example

  • 06_test branche* math.test.ts
import { expect, test } from "bun:test";  

test("2 + 2", () => {  
  expect(2 + 2).toBe(4);  
});  

Elysia

Elisia De Express van / met Bun

bun create elysia app

Elysia 2

  • Performance : You shall not worry about the underlying performance
  • Simplicity : Simple building blocks to create an abstraction, not repeating yourself
  • Flexibility : You shall be able to customize most of the library to fits your need

eenvoudig integratie met swagger


Performance For Loops

branche 07 for loops

start de node versie

node forloop.js

start de bun versie

bun start

Performance server

express bun en elysia

met artillery

ontloopt elkaar niet heel veel

voordelen op openshift?

toon results


Project met Tailwind

toon crm project

voordeel alles wordt razend snel door bun gecompileerd

Bun runt project en de bundle

css wordt gegenereerd door Tailwind


Performance packages en cache

youtube en bun pagina vol met voorbeelden.


Toekomst

Node en Bun zullen voorlopig naast elkaar bestaan

Bun is nog niet productie klaar

Geen Windows versie


Bun en Angular

Installeer new project met ng new projectName daarna cd de map in en bun i
De eerste keer duurt dat even lang als npm i.
bun start om het project te starten. Duurt de eerste keer ook even lang als npm start. Als je nu
rm package-lock.json && rm -rf /node_modules
en daarna weer bun i && bun start dan gaat alles wel veel sneller (op mijn systeem bunnen 3s ).
Vooral handig als je snel je node_modules wil verwijderen en weer opnieuw wil installeeren zoals bv bij het upgraden van Angular.


Github

Typescript enum to array

// enum with string values
enum Lines {
    Line1 = 'text1',
    Line2 = 'text2',
    Line3 = 'text3'
}
// enum
enum State {
    Start,
    Running,
    Stop
}

function ToArray(lines: any) {
    return Object.keys(lines)
        .filter(l => typeof l === "string")
        .map(l => lines[l]);
}

const arr = ToArray(Lines);

console.log(ToArray(arr)); //  ["text1", "text2", "text3"]

const arr2 = ToArray(State);

console.log(ToArray(arr2)); // ["Start", "Running", "Stop", 0, 1, 2]  ??? 0, 1, 2 are no strings???

Styling console.log()

Styling in console.log()
console.log("%c%s", "color: white; background-color: orange; font-style: italic;","my message")

%c - format styling
%s - format string
%o - dom object
%O - Javascript object
%i %f %d - numbers

Windows cli check for running at port 1234

netstat -ano | findstr :<PORT>
tskill typeyourPIDhere 
or taskkill /PID 14328 /F

Arrays

Declare Array
let products = [];
let todos = new Array();
The recommended way is to use [] notation to create arrays.

Merge Two Arrays by concat() method
let array1 = [1,2,3];
let array2 = [4,5,6];
let merged = array1.concat(array2);
console.log(merged);
// expected output: Array [1,2,3,4,5,6]
The concat() method is used to merge two or more arrays. This method returns a new array instead to changing the existing arrays.

ES6 Ways to merge two array
let array1 = [1,2,3];
let array2 = [4,5,6];
let merged = [...array1, ...array2];
console.log(merged);
// expected output: Array [1,2,3,4,5,6]
Get the length of Array
To get the length of array or count of elements in the array we can use the length property.

let product = [1,2,3];
product.length // returns 3
Adding items to the end of an array
Let us add some items to the end of an array. We use the push() method to do so.

let product = ['apple', 'mango'];
product.push('banana');
console.log(projects);
// ['apple', 'mango', 'banana']
Adding items to the beginning of an array
let product = ['apple', 'mango'];
product.unshift('banana');
console.log(projects);
// ['banana', 'apple', 'mango']
Adding items to the beginning of an array in ES6
let product = ['apple', 'mango'];
product = ['banana', ...product];
console.log(projects);
// ['banana', 'apple', 'mango']
Adding items to the end of an array ES6
let product = ['apple', 'mango'];
product = [...product, 'banana'];
console.log(projects);
// ['apple', 'mango', 'banana']
Remove first item from the array
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array. It returns undefined if the array is empty.

let product = ['apple', 'mango', 'banana'];
let firstValue= product.shift();
console.log(firstValue); // ['mango', 'banana'];
console.log(firstValue); // apple
Remove portion of an array
JavaScript give us slice method to cut the array from any position. The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.

arr.slice([begin[, end]])
Example
var elements = ['Task 1', 'Task 2', 'Task 3', 'Task 4', 'Task 5'];

elements.slice(2) //["Task 3", "Task 4", "Task 5"]
elements.slice(2,4) // ["Task 3", "Task 4"]
elements.slice(1,5) // ["Task 2", "Task 3", "Task 4", "Task 5"]
Remove /adding portion of an array -> splice() method
The splice() method changes the contents of an array by removing existing elements and/or adding new elements. Be careful, splice() method mutates the array.

A detailed reference here at MDN splice method.

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
Parameters
startIndex at which to start changing the array (with origin 0).

deleteCount (Optional)An integer indicating the number of old array elements to remove.

item1, item2, ... (Optional)The elements to add to the array, beginning at the start index. If you don’t specify any elements, splice() will only remove elements from the array.

Return value
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

var months = ['Jan', 'March', 'April', 'June'];months.splice(1, 0, 'Feb');
// inserts at 1st index positionconsole.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']months.splice(4, 1, 'May');
// replaces 1 element at 4th indexconsole.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
Remove last item from the array -> pop() method
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.

var elements = ['Task 1', 'Task 2', 'Task 3'];
elements.pop() // 'Task 3'
console.log(elements) // ['Task 1', 'Task 2'];
Joining arrays -> Join () method
The join() method joins all elements of an array (or an array-like object) into a string and returns this string. This is a very useful method.

var elements = ['Task 1', 'Task 2', 'Task 3'];console.log(elements.join());
// expected output: Task 1,Task 2,Task 3console.log(elements.join(''));
// expected output: Task 1Task 2Task3console.log(elements.join('-'));
// expected output: Task 1-Task 2-Task 3
Looping through array
There are various ways to loop through an array. Let’s see the simple example first.

Looping through array — forEach Loop
The forEach loop takes a function, a normal or arrow and gives access to the individual element as a parameter to the function. It takes two parameters, the first is the array element and the second is the index.

let products = ['apple', 'mango'];
products.forEach((e) => {
console.log(e);
});
// Output
// apple
// mango
let products = ['apple', 'mango'];
products.forEach(function (e) {
console.log(e);
});
// Output
// apple
// mango
Let’s see how we can access the index in forEach. Below I am using the arrow function notation, but will work for es5 function type as well.

products .forEach((e, index) => {
console.log(e, index);
});

// Output
// apple 0
// mango 1
Finding Elements in an array — find method
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

The syntax is given below.

callback — Function to execute on each value in the array, taking three arguments
***** element — The current element being processed in the array
***** index (optional) — The index of the current element
***** array (optional) — The array find was called upon.
thisArg (optional) — Object to use as this when executing callback.
Return value
A value in the array if any element passes the test; otherwise, undefined.

arr.find(callback[, thisArg])var data = [51, 12, 8, 130, 44];var found = data.find(function(element) {
return element > 10;
});console.log(found); // expected output: 51
Looping through an array — for in Loop
A for...in loop only iterates over enumerable properties and since arrays are enumerable it works with arrays.

The loop will iterate over all enumerable properties of the object itself and those the object inherits from its constructor’s prototype (properties closer to the object in the prototype chain override prototypes’ properties).

More reading at MDN for in loop

let products = ['apple', 'mango'];
for(let index in products) {
console.log(projects[index]);
}

// Output
// apple
// mango
Note in the above code, a new index variable is created every time in the loop.

Looping through array — map function ()
The map() function allows us to transform the array into a new object and returns a new array based on the provided function.

It is a very powerful method in the hands of the JavaScript developer.

NOTE: Map always returns the same number of output, but it can modify the type of output. For example, if the array contains 5 element map will always return 5 transformed element as the output.

let num = [1,2,3,4,5];
let squared = num.map((value, index, origArr) => {
return value * value;
});
The function passed to map can take three parameters.

squared — the new array that is returned
num — the array to run the map function on
value — the current value being processed
index — the current index of the value being processed
origArr — the original array
Map () — Example 1 — Simple
let num = [1,2,3,4,5];let squared = num.map((e) => {
return e * e;
});
console.log(squared); // [1, 4, 9, 16, 25]
In the above code, we loop through all elements in the array and create a new array with the square of the original element in the array.

A quick peek into the output.

Map () — Example 2— Simple Transformation
Let us take an input object literal and transform it into key-value pair.

For example, let’s take the below array

let projects = ['Learn Spanish', 'Learn Go', 'Code more'];
and transform into key-value pair as shown below.

{
0: "Learn Spanish",
1: "Learn Go",
2: "Code more"
}
Here is the code for the above transformation with the output.

let newProjects = projects.map((project, index) => {
return {
[index]: project
}
});
console.log(newProjects); // [{0: "apple"}, {1: "mango"},]
Map () — Example 3 — Return a subset of data
Lets take the below input

let tasks = [
{ "name": "Learn Angular",
"votes": [3,4,5,3]
},
{ "name": "Learn React",
"votes": [4,4,5,3]
},
];
The output that we need is just the name of the tasks. Let’s look at the implementation

let taskTitles = tasks.map((task, index, origArray) => {
return {
name: task.name
}
});

console.log(taskTitles); //
Looping through an array — filter function ()
Filter returns a subset of an array. It is useful for scenarios where you need to find records in a collection of records. The callback function to filter must return true or false. Return true includes the record in the new array and returning false excludes the record from the new array.

It gives a new array back.

Let’s consider the below array as an input.

let tasks = [
{ "name": "Learn Angular",
"rating": 3
},
{ "name": "Learn React",
"rating": 5
},
{ "name": "Learn Erlang",
"rating": 3
},
{ "name": "Learn Go",
"rating": 5
},];
Now lets use the filter function to find all tasks with a rating of 5.

Let’s peek into the code and the result.

let products = [
{
"name" : "product 1",
"rating" : 5
},
{
"name" : "product 2",
"rating" : 4
},
{
"name" : "product 3",
"rating" : 5
},
{
"name" : "product 4",
"rating" : 2
}
];
let filteredProducts = products.filter((product) => {
return product.rating === 5;
});
console.log( filteredProducts );
// [{"name" : "product 1","rating" : 5},{"name" : "product 3", "rating" : 5}]
Since we are only using one statement in the filter function we can shorten the above function as shown below.

tasks.filter(task => task.rating === 5);
NOTE: Filter function cannot transform the output into a new array.

Looping through an array — reduce function ()
Reduce function loops through array and can result a reduced set. It is a very powerful function, I guess, more powerful than any other array methods (though every method has its role).

From MDN, The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Reduce — Simple Example — 1
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer)); // expected output: 10// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
Note: The first time the callback is called, accumulator and currentValue can be one of two values. If initialValue is provided in the call to reduce(),

then accumulator will be equal to initialValue, and currentValue will be equal to the first value in the array. If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

The reason reduce is very powerful is because just with reduce() we can implement our own, map(), find() and filter() methods.

Using reduce to categorize data
Assume you have the below data structure which you would like to categorize into male and female dataset.

let data = [
{name: "Raphel", gender: "male"},
{name: "Tom", gender: "male"},
{name: "Jerry", gender: "male"},
{name: "Dorry", gender: "female"},
{name: "Suzie", gender: "female"},
{name: "Dianna", gender: "female"},
{name: "Prem", gender: "male"},
];
And we would like the output to be as below

{"female" : [
{name: "Dorry", gender:"female"},
{name: "Suzie", gender: "female"},
{name: "Dianna", gender: "female"},
],
"male" : [
{name: "Raphel", gender:"male"},
{name: "Tom", gender:"male"},
{name: "Jerry", gender:"male"},
{name: "Prem", gender:"male"},
]
}
So, lets get to the code and understand how to achieve the above categorization.

let genderwise = data.reduce((acc,item, index) => {
acc[item.gender].push(item);
return acc;
}, {male: [], female:[]});console.log(genderwise);
The important point above is the reduce function can be initialized with any type of starting accumulator, in the above case an object literal containing

{ male: [], female: []}
I hope this is sufficient to demonstrate the power of reduce method.

Using reduce to implement custom map() function
function map(arr, fn) {
return arr.reduce((acc, item) => [...acc, fn(item)], []);
}
The above is the implementation of custom map function. In the above function we are passing empty array [] as the initial value for the accumulator and the reduce function is returning a new array with the values from the accumulator spread out and appending the result of invoking the callback function with the current item.

Using reduce to implement custom filter() function
Let’s implement the filter() method using reduce().

function filter (arr, fn) {
return arr.reduce(function (acc, item, index) {
if (fn(item, index)) {
acc.push(item);
}
return acc;
},[]);
}
Let’s see the usage and the output below. I could have overwritten the original Array.prototype.filter, but am doing so to avoid manipulating built-in methods.

Using reduce to implement custom forEach function
Let us know implement our own forEach function.

function forEach(arr, fn) {
arr.reduce((acc, item, index) => {
item = fn(item, index);
}, []);
}
The implementation is very simple compared to other methods. We just grab the passed in array and invoke the reduce, and return the current item as a result of invoking the callback with the current item and index.

Using reduce to implement custom pipe() function
A pipe function sequentially executes a chain of functions from left to right. The output of one function serves as the input to the next function in the chain.

Implementation of pipe function

function pipe(...fns) {
// This parameters to inner functions
return function (...x) {
return fns.reduce((v, f) => {
let result = f(v);
return Array.isArray(result) ? result: [result];
},x)
}
}
Usage
const print = (msg) => {
console.log(msg);
return msg;
}
const squareAll = (args) => {
let result = args.map((a) => {
return a * a;
});
return result;
}
const cubeAll = (args) => {
let result = args.map((a) => {
return a * a * a;
});
return result;
}
pipe(squareAll,cubeAll, print)(1,2,3); // outputs => [1, 64, 729]

Holes in arrays
Holes in arrays means there are empty elements within the array. This may be because of couples of operations like delete or other operations that left these holes accidentally.

Now having ‘holes’ in an array is not good from a performance perspective. Let us take an example below.

let num = [1,2,3,4,5]; // No holes or gapsdelete num[2]; // Creates holesconsole.log (num); [1, 2, empty, 4, 5]
So, do not use delete method on array, unless you know what you are doing. delete method doesn’t alter the length of the array.

You can avoid holes in an array by using the array methods splice(), pop() or shift() as applicable.

Changing array length and holes
You can quickly change the length of the array as below.

let num = [1,2,3,4,5]; // length = 5;
num.length = 3; // change length to 3//The below logs outputs
// [1,2,3] -> The last two elements are deleted
console.log(num);
Now, increasing the length this way creates holes.

let num = [1,2,3,4,5];num.length = 10; // increase the length to 10
console.log(num); // [1, 2, 3, empty × 10]
Quickly Fill Arrays
Let’s take a look at how to quickly fill or initialize an array.

The Array.prototype.fill() method
The fill method (modifies) all the elements of an array from a start index (default zero) to an end index (default array length) with a static value. It returns the modified array.

Description
The fill method takes up to three arguments value, start and end. The start and endarguments are optional with default values of 0 and the length of the this object.

If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end.

fill is intentionally generic, it does not require that its this value be an Array object.

fill is a mutable method, it will change this object itself, and return it, not just return a copy of it.

When fill gets passed an object, it will copy the reference and fill the array with references to that object.

Example 1 — Simple fill
new Array(5).fill(“hi”)
//Output => (5) [“hi”, “hi”, “hi”, “hi”, “hi”]
Example 2 — Fill with object
new Array(5).fill({'message':'good morning'})
// Output
// [{message: "good morning"}, {message: "good morning"} , {message: "good morning"} , {message: "good morning"} , {message: "good morning"}]
Example 3 — Generate sequence
Array(5).fill().map((v,i)=>i);
The output will be

[0,1,2,3,4,5]
Example 4— More examples
[1, 2, 3].fill(4); // [4, 4, 4]
[1, 2, 3].fill(4, 1); // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2); // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3); // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2); // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5); // [1, 2, 3]
Array(3).fill(4); // [4, 4, 4]
The Array.from method (static method)
The Array.from() function is an inbuilt function in JavaScript which creates a new array instance from a given array. In case of a string, every alphabet of the string is converted to an element of the new array instance and in case of integer values, new array instance simple take the elements of the given array.

Syntax

Array.from(object, mapFunction, thisValue)
Example 1 — Simple example
console.log(Array.from('foo'));
The output will be

["f", "o", "o"]
Example 2 — Object length
Array.from({ length: 5 });
The output will be

[undefined, undefined, undefined, undefined, undefined]

Tags: 

RxJs

useful site to exercise: Stephen Grider RxJs playground

const { fromEvent } = Rx;
const { map, pluck } = RxOperators;

const input = document.createElement('input');
const container = document.querySelector('.container');
container.appendChild(input);

const observable = fromEvent(input, 'input')
.pipe(
    pluck('target','value'),
  map(value=>parseInt(value)),
  map(value => {
    if(isNaN(value)){
        throw Error('The input must be a number.')
    }
    return value;
  })
);

observable.subscribe({
    next(value){
    console.log('You inserted '+value);
  },
  error(err){
    console.error('error : '+err.message);
  },
  complete(){},
});

observable;

result:

[Log] You inserted 1
[Log] You inserted 12
[Log] You inserted 123
Tags: 

Custom order in sorting, dutch alphabet 'ij' problem

const compareIJ =  (x, y) => {
  var a = x.toLowerCase()
  var b = y.toLowerCase()
  // combined char i+j
  if (a.startsWith('ij') && b.startsWith('i') ) {
    return -1
  } else if (a.startsWith('ij') && b.startsWith('j')){
    return 1
  }
  if (a.startsWith('i') && b.startsWith('ij')) {
    return -1
  } else if (a.startsWith('j') && b.startsWith('ij')){
    return 1
  }


  return 0;
}

const customSort = ({data, sortBy}) => {
  const sortByObject = sortBy.reduce(
    (arr, item) => {
      arr.push(item)
      return arr
    }, [])

  return data.sort((a, b) => {
    return sortByObject.indexOf(a[0]) - sortByObject.indexOf(b[0])
  }).sort(compareIJ)
}

var items = ['wer', 'qwe','ijsdf','lkj','fgh','asdf','bsdfs','csdf','ijsaasdf','isdf','ijsdf', 'jsdf', 'ksdf', 'wer', 'qwe']
const dutchAlphabet = ['a','b','c','d','e','f','g','h','i','ij','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

var a = customSort({data: items, sortBy: dutchAlphabet})

console.log(a)

Tags: 

Angular

install angular cli

nom i angular-cli

create new project

ng new <project-name>

start proj

ng serve
ng s

generate component

ng g c <optional-folder/component-name>

component field - html prop

two way binding

<my-cmp [(title)]="name">

in component.ts

selector decorator:

@Component({
  selector: '.app-servers',
...
})

in html:

<!--selector "app-servers"-->
<app-servers></app-servers>

<!--selector "[app-server]" as attribute-->
<div app-servers></div>

<!--selector ".app-server" as className-->
<div class="app-servers"></div>

varname: type, ex: name: string;
or object (define class in folder models, like ObjectClass class { var a: number; }):
objectclass: ObjectClass

in .html

{{varname}} , ex: {{name}}
{{objectclass.a}}

component input @input()

<input [value]="my_name">

in parent-component .html

<component-name [name]="my_name" ....  

in component-name .ts

export component-name class {

@Input()
name: string;
...
}

events

in component .html

<button (click)="functionname($event)">button title</button>

in .ts
create function functionname($event)

export class ComponentClass {  
  ...  
  constructor(){}  
  ...  
 functionname(event: any) {  
  //do something  
  }  
  ...  
}  

Attribute Directives

<p appHighlight>Highlight me!</p>

ng g directive

to use it like [appClass] style of writing:

<li class="page-item"
        [appClass]="{'disabled':currentPage===images.length-1}">
</li>
import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appClass]'
})
export class ClassDirective {

  constructor(private element: ElementRef) { }

  @Input('appClass') set classNames(classObj: any) {
    for (const key in classObj) {
      if (classObj[key]) {
        this.element.nativeElement.classList.add(key);
      } else {
        this.element.nativeElement.classList.remove(key);

      }
    }
  }
}

Structural Directives

What are structural directives?

Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.
As with other directives, you apply a structural directive to a host element. The directive then does whatever it's supposed to do with that host element and its descendants.
Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name as in this example.

<div *ngIf="hero" class="name">{{hero.name}}</div>

The three common structural directives are ngIf ngFor ngSwitch

struct directive creation

ng g directive <directive-name>

to use like *appTimes

<ul *appTimes="5">
  <li>hi there!</li>
</ul>
import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
// structural directive
@Directive({
  selector: '[appTimes]'
})
export class TimesDirective {

  constructor(
    private viewContainer: ViewContainerRef,
    private templateRef: TemplateRef<any>
  ) { }

  @Input('appTimes') set render(times: number) {
    this.viewContainer.clear();

    for (let i = 0 ; i < times; i++) {
      this.viewContainer.createEmbeddedView(this.templateRef, {
        index: i
      });
    }
  }
}

ngFor

<ul>  
  <li *ngFor="let item of items; index as i">  
    {{i+1}} {{item}}  
  </li>  
</ul>  

The following exported values can be aliased to local variables:
- $implicit: T: The value of the individual items in the iterable (ngForOf).
- ngForOf: NgIterable: The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe (userStreams | async).
- index: number: The index of the current item in the iterable.
- first: boolean: True when the item is the first item in the iterable.
- last: boolean: True when the item is the last item in the iterable.
- even: boolean: True when the item has an even index in the iterable.
- odd: boolean: True when the item has an odd index in the iterable.

ngIf

shorthand

<div *ngIf="condition">Content to render when condition is true.</div>

extended

<ng-template [ngIf]="condition"><div>Content to render when condition is true.</div></ng-template>  

with else block

<div *ngIf="condition; else elseBlock">Content to render when condition is true.</div>  
<ng-template #elseBlock>Content to render when condition is false.</ng-template>  

if then else

<div *ngIf="condition; then thenBlock else elseBlock"></div>  
<ng-template #thenBlock>Content to render when condition is true.</ng-template>  
<ng-template #elseBlock>Content to render when condition is false.</ng-template>  

with value locally

<div *ngIf="condition as value; else elseBlock">{{value}}</div>  
<ng-template #elseBlock>Content to render when value is null.</ng-template>  

else in template, use #

<div class="hero-list" *ngIf="heroes else loading">  
 ...   
</div>  

<ng-template #loading>  
 <div>Loading...</div>  
</ng-template>

ngClass

Adds and removes CSS classes on an HTML element.

The CSS classes are updated as follows, depending on the type of the expression evaluation:
string - the CSS classes listed in the string (space delimited) are added,
Array - the CSS classes declared as Array elements are added,
Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

<some-element [ngClass]="'first second'">...</some-element>  

<some-element [ngClass]="['first', 'second']">...</some-element>  

<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>  

<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>  

<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>  

ngSwitch

A structural directive that adds or removes templates (displaying or hiding views) when the next match expression matches the switch expression.

<container-element [ngSwitch]="switch_expression">
  <!-- the same view can be shown in more than one case -->
  <some-element *ngSwitchCase="match_expression_1">...</some-element>
  <some-element *ngSwitchCase="match_expression_2">...</some-element>
  <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
  <!--default case when there are no matches -->
  <some-element *ngSwitchDefault>...</some-element>
</container-element>
<container-element [ngSwitch]="switch_expression">
      <some-element *ngSwitchCase="match_expression_1">...</some-element>
      <some-element *ngSwitchCase="match_expression_2">...</some-element>
      <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element>
      <ng-container *ngSwitchCase="match_expression_3">
        <!-- use a ng-container to group multiple root nodes -->
        <inner-element></inner-element>
        <inner-other-element></inner-other-element>
      </ng-container>
      <some-element *ngSwitchDefault>...</some-element>
    </container-element>

ng-container

The Angular is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

ng-tempplate

renders only the hero-detail.

<template [ngIf]="currentHero">  
  <hero-detail [hero]="currentHero"></hero-detail>  
</template>  

pipes for extending func

formatting strings, dates, numbers, upper, lower, etc

date

{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}

Examples are given in en-US locale.
'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
'shortDate': equivalent to 'M/d/yy' (6/15/15).
'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
'shortTime': equivalent to 'h:mm a' (9:03 AM).
'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

{{ dateObj | date }}               // output is 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output is 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output is '9:43 PM'
{{ dateObj | date:'mm:ss' }}       // output is '43:11'

LowerCasePipe

{{ value_expression | lowercase }}

simular as UpperCasePipe, TitleCasePipe

PercentPipe

{{ value_expression | percent [ : digitsInfo [ : locale ] ] }}

<!--output '26%'-->  
    <p>A: {{a | percent}}</p>  

    <!--output '0,134.950%'-->  
    <p>B: {{b | percent:'4.3-5'}}</p>  

    <!--output '0 134,950 %'-->  
    <p>B: {{b | percent:'4.3-5':'fr'}}</p>  

SlicePipe

<li *ngFor="let i of collection | slice:1:3">{{i}}</li>
...
    <p>{{str}}[0:4]: '{{str | slice:0:4}}' - output is expected to be 'abcd'</p>  
    <p>{{str}}[4:0]: '{{str | slice:4:0}}' - output is expected to be ''</p>  
    <p>{{str}}[-4]: '{{str | slice:-4}}' - output is expected to be 'ghij'</p>  
    <p>{{str}}[-4:-2]: '{{str | slice:-4:-2}}' - output is expected to be 'gh'</p>  
    <p>{{str}}[-100]: '{{str | slice:-100}}' - output is expected to be 'abcdefghij'</p>  
    <p>{{str}}[100]: '{{str | slice:100}}' - output is expected to be ''</p>  

AsyncPipe

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

@Component({
  selector: 'async-promise-pipe',
  template: `<div>
    promise|async: 
    <button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button>
    <span>Wait for it... {{ greeting | async }}</span>
  </div>`
})
export class AsyncPromisePipeComponent {
  greeting: Promise<string>|null = null;
  arrived: boolean = false;

  private resolve: Function|null = null;

  constructor() { this.reset(); }

  reset() {
    this.arrived = false;
    this.greeting = new Promise<string>((resolve, reject) => { this.resolve = resolve; });
  }

  clicked() {
    if (this.arrived) {
      this.reset();
    } else {
      this.resolve !('hi there!');
      this.arrived = true;
    }
  }
}

ViewChild, ViewChildren

A template reference variable as a string (e.g. query with @ViewChild('cmp'))
Any provider defined in the child component tree of the current component (e.g. @ViewChild(SomeService) someService: SomeService)
Any provider defined through a string token (e.g. @ViewChild('someToken') someTokenVal: any)
A TemplateRef (e.g. query with @ViewChild(TemplateRef) template;)

Directive, decorator

Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behavior to elements in the DOM.
like 'placeholder' in

<input value="abc" **placeholder**="firstname">  

reusable in whole project

creation

ng g directive directives/HighlightedDirective

@HostBinding @HostListener

or emit directive to other components:

@Input('highlighted')
  isHighlighted = false;

  @Output()
  toggleHighlight = new EventEmitter();

  constructor() {
    //console.log('highlighted created...');
  }

  @HostBinding('class.highlighted')
  get cssClasses() {
    return this.isHighlighted;
  }

  @HostBinding('attr.disabled')
  get disabled() {
    return "true";
  }

  @HostListener('mouseover', ['$event'])
  mouseover($event) {
    console.log($event);
    this.isHighlighted = true;
    this.toggleHighlight.emit(this.isHighlighted);
  }

toggle() {
    this.isHighlighted = !this.isHighlighted;
    this.toggleHighlight.emit(this.isHighlighted);
  }

Structural Directives

ng g directive directive/ngx-name

nix-name

ngxNameDirective
results to template

import { Directive,  TamplateRef } from '@angular/core';

@Directive({
  selector: {'[ngxngxName]'}
})
export class NgxNameDirective {

  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {

  }

  @Input()
  set ngxName(condition:booleam);
}

Angular Injectable Services

Modules

ng g m MODULE_NAME (--routing)

Webpack notes

- Webpack-dev-server
- Rimraf, cleanup build files
- Commonschunkplugin manifest
- Chunkhash
- Htmlwebpackplugin

var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

const VENDOR_LIBS = [
  'react', 'lodash', 'redux', 'react-redux', 'react-dom',
  'faker', 'react-input-range', 'redux-form', 'redux-thunk'
];

module.exports = {
  entry: {
    bundle: './src/index.js',
    vendor: VENDOR_LIBS
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].[chunkhash].js'
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    }),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest']
    }),
    new HtmlWebpackPlugin({
      template: 'src/index.html'
    })
  ]
};

Tags: 

Cypress tests

notes from new es6

probeer in:
http://jsbin.com/

imports

You got two different types of exports: default (unnamed) and named exports:

default => export default ...;

named => export const someData = ...;

You can import default exports like this:

import someNameOfYourChoice from './path/to/file.js';

Named exports have to be imported by their name:

import { someData } from './path/to/file.js'

snips

const myName = 'hjh';
///console.log(myName);

function printName(name){
  console.log(name);
}
const printName2 = (name,age) =>{
  console.log('2: '+name+' age: '+age);
}
//printName("hhhh");
//printName2("hhhh");

const multiply = (number) =>{
  return number * 2;
}
const multiply2 = number => number * 2;

//printName(multiply(4));
//printName(multiply2(4));

class Person{
 
  constructor(name){
    this.name = name;
  }
 
  call() {
    console.log( 'hi from '+ this.name);
  }
}
const p = new Person('hjc');
p.call();

const numbers = [1,2,3];
//spread
const newNumbers = [...numbers,4];
console.log('newNumbers: '+newNumbers);
const newPerson = {
  ...p,
  age: 26
}
console.log(newPerson)

const filter = (...args) => {
  return args.filter(el => el === 1);
}

console.log('filter : '+filter(1,2,3));

[num1,num2] = numbers;
console.log(num1,num2);

// Arrrays & Class's are copied by reference!

const person3 = {
  name: 'Max'
}

const person4 = person3;
const person5 = {
  ...person3
}
person3.name = 'Manu';

console.log(person4);
console.log(person5);

// array .map function
const doubleNumbers = numbers.map((num)=> {return num*2});
console.log('double numbers '+doubleNumbers);

meer array functions
map() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
find() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
findIndex() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
filter() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
reduce() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
concat() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
slice() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...
splice() => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global...

react components playground:
https://codepen.io

Tags: 

React Native notes

Lifecycle
constructor(props) {
super(props);
}
render (){}

componentDidMount() {}
componentDidUpdate() {}
componentWillUnmount() {}

React with typoscript
# Make a new directory
$ mkdir react-typescript

# Change to this directory within the terminal
$ cd react-typescript

# Initialise a new npm project with defaults
$ npm init -y

# Install React dependencies
$ npm install react react-dom

# Make index.html and App.tsx in src folder
$ mkdir src
$ cd src
$ touch index.html
$ touch App.tsx

# Open the directory in your favorite editor
$ code .

then index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>React + TypeScript</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div id="main"></div>
<script src="./App.tsx"></script>
</body>
</html>

# Install Parcel to our DevDependencies
$ npm i parcel-bundler -D

# Install TypeScript
$ npm i typescript -D

# Install types for React and ReactDOM
$ npm i -D @types/react @types/react-dom

add to pack.json
"scripts": {
"dev": "parcel src/index.html"
},

create Counter.tsx

import * as React from 'react';

export default class Counter extends React.Component {
    state = {
        count: 0
    };

    increment = () => {
        this.setState({
            count: (this.state.count += 1)
        });
    };

    decrement = () => {
        this.setState({
            count: (this.state.count -= 1)
        });
    };

    render () {
        return (
            <div>
                <h1>{this.state.count}</h1>
                <button onClick={this.increment}>Increment</button>
                <button onClick={this.decrement}>Decrement</button>
            </div>
        );
    }
}

app.tsx

import * as React from 'react';
import { render } from 'react-dom';

import Counter from './Components/Counter';

render(<Counter />, document.getElementById('main'));

run:
$ npm run dev

nodejs express

npm init

npm install express --save
npm install body-parser --save
npm install nodemon --save / --g
npm install bcryptjs --save

create app.js

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('listening on port 3000')
})

Tags: 

Sails js 2

Sailsjs for backend rest api

==
help with salsas:

  • Google Groups: sails.js
  • IRC: #sailsjs
  • Stack Overflow (using tag sails.js)

==
instal

mac:
nodejs.org
download pkg
(
/usr/local/bin/node
/usr/local/bin/npm
add to $PATH
/usr/local/bin
)

(sudo) npm install sails –global

==
setup first project
sails new firstApp

move to folder
cd firstApp

to start sails:
sails lift

generate new model via blueprint engine
sails generate api user

then question about migrate on sails lift
choose alter in non Prod env
change firstApp/config/model.js

module.exports.models = {
migrate: 'alter'
};

http://localhost:1337/user
first results
in json response []

localhost:1337/user/create?name=HJSnips
results in

[
 
  {
    "name": "HJSnips",
    "createdAt": "2016-03-30T07:30:39.555Z",
    "updatedAt": "2016-03-30T07:30:39.555Z",
    "id": 1
  }
]

==
use Sails built-in integration
with websockets and Socket.io

create
firstApp/assets/js/test.js

io.socket.get('/user', function (users){ console.log(users);});
io.socket.on('user', function (message) {
console.log("Got message: ", message);
});

==
policies
firstApp/config/policies.js
module.exports.policies = {
'UserController': {
'create': ['sessionAuth']
}
};

==
static assets
npm install sails-generate-static --save

sails generate static

sails lift
now when adding content to assets Grunt will create routes files in .tmp

== css assets
to use css in html via grunt make sure:

<!--STYLES-->
<!--STYLES END-->

are in!

<head>
<title>New Sails App</title>
<!-- Viewport mobile tag for sensible mobile support -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
   
<!--STYLES-->
<!--STYLES END-->
</head>

<html>
<body>
<!--STYLES-->
<!--STYLES END-->
</head>
<body>
<!--TEMPLATES-->
<!--TEMPLATES END-->
<!--SCRIPTS-->
<!--SCRIPTS END-->
</body>


</html>

Calc days between dates

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);

var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

Tags: 

switch

switch(expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block
}

Tags: 

remove object from array

someArray = [{name:"Kristian", lines:"2,5,10"},
{name:"John", lines:"1,19,26,96"}];
You can use several methods to remove an item from it:

//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0,1); // first element removed
//4
someArray.pop(); // last element removed
If you want to remove element at position x, use:

someArray.splice(x,1);

Tags: 

check string is equal

if ( variable.valueOf()=="string" )

"a" == "b"
However, note that string objects will not be equal.

new String("a") == new String("a")
will return false.

Call the valueOf() method to convert it to a primitive for String objects,

new String("a").valueOf() == new String("a").valueOf()

Tags: 

for each

var a = ["a", "b", "c"];
a.forEach(function(entry) {
console.log(entry);
});

Tags: 

Maze generator

function maze(x,y) {
var n=x*y-1;
if (n<0) {alert("illegal maze dimensions");return;}
var horiz =[]; for (var j= 0; j0 && j0 && (j != here[0]+1 || k != here[1]+1));
}
while (00 && m.verti[j/2-1][Math.floor(k/4)])
line[k]= ' ';
else
line[k]= '-';
else
for (var k=0; k0 && m.horiz[(j-1)/2][k/4-1])
line[k]= ' ';
else
line[k]= '|';
else
line[k]= ' ';
if (0 == j) line[1]= line[2]= line[3]= ' ';
if (m.x*2-1 == j) line[4*m.y]= ' ';
text.push(line.join('')+'\r\n');
}
return text.join('');
}

Tags: 

window size width height

var w = window.innerWidth;
var h = window.innerHeight;

Tags: 

localstorage

local storageif(typeof(Storage)!=="undefined")
{
// Code for localStorage/sessionStorage.
}
else
{
// Sorry! No Web Storage support..
}

random int between

Math.floor((Math.random() * 100) + 1);

Tags: 

set get value from input field

getvar bla = $('#txt_name').val();

set$('#txt_name').val('bla’);

Tags: 

click jquery add target

click

html

Click here

js

$( "#target" ).click(function() {

alert( "Handler for .click() called." );

});

Tags: 

on document load jquery

$( document ).ready(function() {

console.log( "ready!" );

});

Tags: 

on mouse down register x y

var clicking = false;

$('.selector').mousedown(function(){
clicking = true;
$('.clickstatus').text('mousedown');
});

$(document).mouseup(function(){
clicking = false;
$('.clickstatus').text('mouseup');
$('.movestatus').text('click released, no more move event');
})

$('.selector').mousemove(function(){
if(clicking == false) return;

// Mouse click + moving logic here
$('.movestatus').text('mouse moving');
});

Tags: 
Subscribe to RSS - javascript