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

2020-08-15

Javascript ES6 Loops, Map, and Spread Operator

It's been a while (14 years) since I last learn about Javascript, I think at that time still ES5, but since ES6 (=ES2015, released June 2015) and newer ones already out (but most of the browsers already implemented most of ES6 features way before), I think it's time to review one of the features (I think the only features I learned was Promise and async-await few years ago). ES6 introduces new loop syntax for..of:

// old one
for(var k in arrOrObj) // iterate by key

// new one
for(const v of arrOrObj) // iterate by value
for(const v of Object.values(obj)) // iterate by value
for(const kv of Object.entries(obj)) // iterate by key-value pair
for(const [k,v] of Object.entries(obj)) // destructure

 

ES6 also introduces new data structure to store associative array, just like object, but difference:

  • unlike object, you don't have to worry that the key conflict with the object's property
  • iteration guaranteed by original insertion order, as far as I remember Object is random for Chrome and Sorted for Firefox
  • Has .size property, not Array .length
  • key not automatically converted as string, obj['1'] == obj[1]

let map = new Map(); // order by insert
map.set('a',1) // not equal to map['a']=1
map.get('a') // not equal to map['a']
map.has('a')
map.delete('a') // false if not exists

for(const [k,v] of map) // destructure
for(const k of map.keys()) // iterate by key
for(const v of map.values()) // iterate by value

ES6 spread operator also useful when dealing with Map, Object, or Array:

[...map] // get array of key-value pairs
Array.from(map) // get array of key-value pairs
[...map.keys()] // get array of keys
[...map.values()] // get array of values

map = new Map([...Object.entries(obj)].sort()) // order by key

new Map(map) // clone map
new Map([['a',1],['b',2],['c',3]]) // create from array of key-value
new Map([...map1, ...map2]) // merge map 

{...obj} // clone object
{...obj1,...obj2} // merge object

new Array(...arr) // clone array
[...arr] // clone array
[...arr1,...arr2] // concat array


Why not using .forEach method? Because you cannot break early. You can learn about new Javascript features (BigInt, Set, Promise, etc) from MDN.

2020-05-29

Techempower Framework Benchmark Round 19

The result for Techempower framework benchmark round 19 is out, as usual the most important benchmark is the update and multi query benchmark:


This time, C++ (drogon), Rust (actix) are the top tier performer, followed by Java, Javascript (vertx's es4x), PHP (kumbiaphp+workerman), C# (ASP.NET), C (h2o), Kotlin (kooby), Scala (vertx), Go (fasthttp) and C#.



The top performer for multi-query benchmark are: C++, Rust, Java, Scala, JS, Kotlin, PHP, and Go. It's interesting to see that VLang already entered this benchmark but only on plaintext and json serialization benchmark. Compared to previous benchmark, Scala is in, Python, Perl, and Dart are out of the screenshoted top tier for now.

2020-04-10

Svelte Tutorial 1: Introduction to Svelte (English & Indonesia)

English


Svelte is a tool for building fast web applications. It's a competitor to React, Vue, Ember, Aurelia, and Angular, but it's better since it was compiled/errors checked at compile time before combined into a bundle.js file, not needing any virtual DOM/different template file/language like JSX, also because Svelte has the lowest learning curve among all. To learn more why Svelte is better than the rest, see Rich Harris' presentation about Rethinking Reactivity. To create a new svelte project use this command after you installed nodejs, npm, and npx:

npx degit sveltejs/template project1
cd project1
npm install # install dependencies
npm run dev


You can look at the result in the browser, and edit that project directly side by side (it has live reload). In Svelte, an application is composed from one or more components. A component is a reusable self-contained block of code that encapsulates HTML, CSS and JavaScript that belong together, written into a .svelte file. Here are some basics in svelte:

How to declare and use variable


First, add a <script> tag to your component and declare a variable (name)

<script>
let name = 'world';
</script>

Then, we can refer to variable in the markup using curly braces.

<h1>Hello {name}!</h1>

We can also use curly braces to put any JS we want.

How to create dynamic attributes:


We can use variable to create dynamic attributes:

<script>
let src = 'tutorial/image.gif';
</script>
<img src={src}>

We can use variable to specify image source, so we can dynamically determine link source programmatically for example.

You can also use shorthand feature when variable name and attribute is the same, like this:

<img {src}>

Styling


Just like in HTML, you can add a <style> tag to your component:

<style>
p {
color: purple;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>


<p>This is a paragraph.</p>

What is special in svelte is style is scoped within component so when you set <p> style in one component, it wont accidentally change <p> style elsewhere within your app.

Nested component


It would be impractical to put your entire app in a single component. Instead, we can import components from other files and include them as though we were including elements.

For example we can have file Nested.svelte like this:

<p>This is another paragraph.</p>

Then we can use Nested component by importing it like this:

<script>
import Nested from './Nested.svelte';
</script>

Nested in this case can be anything, and totally independent to the file name (So you can name it anything, but it's a good practice to import with same name as the file name). And when we want to use it, just use it like you would when using predefined tags

<p>This is a paragraph.</p> <!-- normal predefined tag -->

<Nested/>                   <!-- your made up tag -->

Notice that even though both  <p> and <Nested> actually used same  <p> tag, but each style is independent as now its considered different component. One more thing to remember, tag name is case sensitive, so <Nested> not the same with <nested>

Unescaping HTML tags


Ordinarily, strings are inserted as plain text, meaning that characters like < and > have no special meaning. But sometimes you need to render HTML directly into a component. For example, the words you're reading right now exist in a markdown file that gets included on this page as a blob of HTML.

<script>
let str = `string contains <strong>HTML!!!</strong>`;
</script>

So instead of doing this:

<p>{str}</p>

In Svelte, you can do this with the special {@html ...} tag:

<p>{@html str}</p>



Indonesia


Svelte adalah alat untuk membuat web application secara cepat. Svelte adalah pesaing dari ReactVueEmberAurelia, and Angular, tapi svelte kami nilai lebih baik karena dicompile dan dicek error nya saat compile, baru kemudian digabungkan dalam file bundle.js, dan tidak membutuhkan virtual DOM atau file/bahasa template yang berbeda seperti JSX, svelte juga termasuk yang paling mudah dipelajari dibanding yang lainnya. Untuk lebih meyakinkan kenapa Svelte lebih baik dari yang lain, kamu bisa tonton persentasi Rich Harris tentang Rethinking Reactivity. Untuk membuat project Svelte yang baru gunakan perintah ini sesudah kamu menginstall nodejs, npm, dan npx:

npx degit sveltejs/template project1
cd project1
npm install # install dependencies
npm run dev


Kamu bisa melihat hasil web mu di browser, dan meng edit project itu langsung secara berdampingan (Svelte punya live reload). Di dalam svelte aplikasi dibentuk dari satu atau lebih komponen. sebuah komponen adalah blok program yang berdiri sendiri dan bisa digunakan berulang kali, yang terdiri atas HTML, CSS dan Javascript yang saling berhubungan, dikumpulkan menjadi satu dalam file .svelte. Berikut adalah dasar-dasar dalam Svelte:

Cara mendeklarasi dan menggunakan variabel

Pertama, tambahkan tag <script> dan deklarasikan variabel (name)

<script>
let name = 'world';
</script>

Kemudian kita bisa menggunakan variabel di dalam markup menggunakan kurung kurawal.

<h1>Hello {name}!</h1>

Kita juga bisa menggunakan kurung kurawal untuk memasukkan program JS.

Cara membuat atribut yang dinamis


Kita bisa menggunakan variabel untuk membuat atribut yang dinamis:

<script>
let src = 'tutorial/image.gif';
</script>
<img src={src}>

Karena kita bisa menggunakan variabel untuk memasukkan alamat asal image, maka kita bisa mengatur alamatnya secara dinamis dalam pemrograman.

Kita juga bisa menggunakan cara singkat jika nama variabel dan nama atributnya sama, seperti ini:

<img {src}>

Styling


Sama persis seperti di HTML, kamu juga bisa menambahkan tag  <style> ke komponen yang kamu buat.

<style>
p {
color: purple;
font-family: 'Comic Sans MS', cursive;
font-size: 2em;
}
</style>

<p>This is a paragraph.</p>

Yang istimewa dari svelte adalah style yang kamu tambahkan akan dibatasi hanya di dalam komponen tersebut, jadi misal dalam contoh di atas, style warna ungu tidak akan merubah style <p> lainnya dalam aplikasi buatanmu.

Nested component


Untuk tujuan pembuatan aplikasi yang baik, alangkah baiknya apabila kita tidak memasukkan smua app kita dalam satu komponen saja, melainkan bisa dipecah-pecah menjadi beberapa komponen kecil yang bisa digunakan berulang kali apabila dibutuhkan di kemudian hari. Kita bisa import komponen yang sudah dibuat tadi dari file lain dan di include kan seperti jika kita meng include kan elemen.

Sebagai contoh jika kita mempunya file Nested.svelte yang isinya seperti ini:

<p>This is another paragraph.</p>

Maka kita bisa memasukkan komponen Nested dengan cara import seperti ini:

<script>
import Nested from './Nested.svelte';
</script>

Nama elemen Nested bisa saja dirubah dengan nama lain, jadi nama ini tidak berhubungan dengan nama file nya (tapi akan jadi kebiasaan yang lebih baik jika dinamakan sama saja dengan nama file nya, supaya tidak bingung sendiri begitu maksudnya). Kemudian jika mau menggunakan tinggal gunakan dengan cara yang sama seperti menggunakan tag HTML pada umumnya.

<p>This is a paragraph.</p> <!-- html normal -->

<Nested/>                   <!-- tag buatan sendiri -->

Perhatikan meskipun kedua <p> dan <Nested> sebenarnya sama2 menggunakan tag <p>, tapi style masing2 tidak akan saling mempengaruhi, karena sekarang mereka sudah dianggap sebagai komponen yang berbeda. Satu lagi yang harus diingat, nama komponen buatanmu sifatnya case sensitive, jadi <Nested>  tidak sama dengan <nested>

Unescaping tag HTML


Biasanya, string akan dianggap sebagai plain text, jadi jika di dalam string itu ada karakter seperti   < dan > maka tidak akan dianggap sebagai sesuatu yang istimewa. Tapi kadang kita memang ingin menganggapnya sebagai HTML dan memasukkan langsung ke dalam komponen. Sebagai contoh kata-kata yang dimasukkan mengandung tag <strong>, supaya tulisan jadi bold.

<script>
let str = `string contains <strong>HTML!!!</strong>`;
</script>

Maka daripada memasukkan variabel seperti biasa dengan kurung kurawal:

<p>{str}</p>

Di svelte kita bisa melakukan dengan tag {@html ...} seperti ini, maka tulisan akan mengandung bold di bagian yang ada tag <strong>:

<p>{@html str}</p>

2019-12-20

State of Svelte UI Libraries

Awesome list of Svelte component libraries, which is CSS Framework that have Svelte integration. Here's the comparison among them all:

Component SvelteStrap 3.2.8 Svelma Bulma Components Svelte-MUI Svelte-Chota Smelte
Based on https://getbootstrap.com/ https://bulma.io/ https://bulma.io/ https://material.io/ https://jenil.github.io/chota/ https://material.io/
URL https://bestguy.github.io/sveltestrap/ https://c0bra.github.io/svelma/install http://svelte-bulma-components.surge.sh/ https://svelte-mui.ibbf.ru/ https://alexxnb.github.io/svelte-chota/ https://smelte.netlify.com/
Layout Container, Row, Col div.tile

Container, Row, Col
Alert/Flash/Toast Alert, Toast Message, Notification, Snackbar.(), Toast.()
Snackbar
Snackbar
Breadcrumb Breadcrumb




Buttons Button

Button, ButtonGroup Button Button
Card Card article.media

Card Card
Animation Collapse, Fade Collapse
Ripple Details
Dropdown Dropdown
Dropdown

Select
Forms Form, FormGroup, Label, Input Field, Input, Switch
CheckBox, Datepicker, Datefield, Textfield, Radio Input, Field, Radio, Checkbox TextField, SearchBar
Jumbotron/Hero Jumbotron section.hero



List ListGroup



List
Modal/Dialog Modal Dialog.(), Modal Modal Dialog Modal Dialog
Nav/Tabs/Pills/Acordion Nav Tabs TabsContainer ExpansionPanel, Menu Nav, Tabs Tabs, Menu
NavBar with Mobile NavBar
Navbar Sidepanel
NavigationDrawer
Pagination Pagination
Pagination


Progress Progress, Spinner Progress


PorgressLinear, ProgressCircular
Table Table table.table


DataTable
Icon
Icon .fa Icon icon*=mdi*, Icon
Tag/Label



Tag Chip
Media Media



Image
Tooltip




Tooltip
Treeview




Treeview


There's also many CSS Framework that doesn't use Javascript such as: TentCSS, Milligram, Mustard, MiniCSS, Bulma, and Chota (on the table).

Update 2020: there's SvelteMaterialUI and IBM Carbon Svelte

Update 2021: Svelte Materialify

2019-07-25

Techempower Framework Benchmark Round 18

Framework Benchmark 18 is out (half year after previous result), the shocking result that Vert.x version of Javascript just killing almost everyone except Rust. Top performing programming languages for updating-database benchmark are: Rust, Java, Javascript, C++, C#, Go, Kotlin, Dart, Python.

For multiple-queries benchmark, the top performers are: Rust, Java, Javascript, C, Kotlin, C++, Clojure, Go, PHP, Perl, C#.

Rust is quite interesting, the only drawback that I found other than the syntax is the slow compile, it took nearly 6 seconds for even a minor changes (with Actix framework) in ramdisk to recompile, even with slow compile flags turned off.

2018-06-12

Costajob HTTP Benchmark

Learning about Pony, a new (at least for me) programming language that designed to be elixir-python-golang like (imho), got me to this page:


It's interesting to see the memory usage of those language-framework, also Crystal, despite inability to utilize multicore still could perform as good as Golang's default muxer (which is not the best).

2018-02-15

TechEmpower Framework Benchmark Round 15

As usual, the only one matters are data updates and multiple queries.

Top ranker languages are C, C++, Java, C#, Dart, Python, Go, Perl, Scala, Javascript.


Top ranker language for multiple queries: Dart, Java, C++, C, Kotlin, Rust, Ur, Go.

Dart seems to be getting more and more popularity, since a framework for cross platform mobile app: Flutter is very usable.

2017-05-11

TechEmpower Framework Benchmark Round 14

New benchmark result is out, as usual the important part is the data-update benchmark:


At that chart, the top ranking language are: Kotlin, C, Java, C++, Go, Perl, Javascript, Scala, C#; and for the database: MySQL, PostgreSQL, MongoDB.

Also the other benchmark that reflect real world case is multiple-queries:
On that benchmmark, the top performer programming language are: Dart, C++, Java, C, Go, Kotlin, Javascript, Scala, Ruby, and Ur; and the database: MongoDB, PostgreSQL, MySQL. You can see the previous result here, and here.


2016-12-09

Javascript ES6 to ES5 Transpiler

When you are so eager to use ES6 features but you know that most browsers not yet implement all ES6 features completely (that's why there are also HTML5 pollyfills). Here's the list of transpiler to convert Javascript ES6 to ES5:
Almost 2 years ago comparison between Babel and Termi. Oh and yes, you can use Babel with WebStorm.
Note that every transpilers (CoffeeScript, TypeScript, Elm, Haxe, etc) suffer the same problem: compile duration (hey, one more thing to do [=minify] before testing/deploying) and hard debugging (easier if you use source maps, only for JS transpilers, I don't know if these things exists for transpiler for other language). Still I wish for wAsm to come faster. Btw I learned ES6 just for react-native-web, otherwise I would always still stick with ES5.


2016-11-16

Techempower Framework Benchmark Round 13

After long wait, the latest Techempower Framework Benchmark 13 is out! And just like previous one, Go's fasthttp really really fast. As usual the most important thing is data updates benchmark:


Top ranker in this part (more than 1024 req/s) are GoC++JavaJavascript (NodeJS)PerlC#, ElixirDartScalaPythonClojure, and Groovy (Actually PHP are there below the last one on the picture with 1018 req/s). And for the database part would be: PostgreSQL, MongoDB, and MySQL.

2016-11-02

Javascript Virtual DOM Framework Benchmark

Recently I found a framework benchmark for javascript (round4 2016-09-12), it shows a lot information. The fastest ranker are:

Framework Version Runtime Ratio (% slower than fastest) MB Start MB 1K rows
vanillajs
1 2.98 4.85
inferno 1.0.0-beta9 3 3.19 6.60
vanillajs-keyed
4 2.98 4.81
dio.js 3.0.5 4 3.19 7.09
domvm 2.0.0-beta 10 3.15 7.43
kivi 1.0.0-rc2 17 3.17 6.69

Also there are another benchmark (this have fewer framework, last result at this time):

Framework Init Time First Render Time Overall Time
kivi[adv] 1.0.0 2,185 25,795 527,703
Inferno 0.7.22 3,340 31,780 553,513
Imba 0.14.3 15,920 26,250 569,895
Bobril 4.38.0 3,430 26,255 682,847
Vidom 0.3.16 3,400 38,220 729,882
Maquette 2.3.3 1,955 27,410 733,165
Snabbdom 0.5.0 2,565 34,710 759,481
React 15.3.1 38,640 56,065 926,403
React-lite 0.15.6 6,345 40,725 1,105,627
Preact 5.4.0 2,550 53,585 1,150,506
Vanilla[innerHTML] 1.0.0 1,790 16,925 1,500,676
Deku 2.0.0-rc16 3,285 45,950 1,598,787
Mercury 14.1.0 2,840 41,325 2,115,253
yo-yo 1.2.2 1,825 21,835 2,295,505

Apparently there are a lot of them around the internet.
Of course you can build your own framework, here's the tips if you plan doing so.

2016-06-19

Flowchart to choose your programming language

Just now, I found a cool site to generate flowchart from source code (just like dot program):

(click for larger picture)

Anyway this just a joke, just like before (if programming language were religion/woman), may odds be in your favor..

Btw here's the code if you want to modify.. please use http://pastie.org if you want to do a long comment containing source code..

Choosing Programming language flowchart;
if(I really really care 
about runtime performance) {
  if(I am masochist..) {
    if(I like Mozilla..) {
      Use Rust;rust-lang.org
    } else {
      Use C++;cplusplus.com
    }
  } else if(I don't want 
  to learn something new..) {
    Use C;cprogramming.com
  } else if(I like long lines..) {
    Use Java;java.com
  } else if(I like FP?) {
    if(But I'm not masochist..) {
      Use Scala;scala-lang.org;
    } else if(I like parentheses..) {
      Use Clojure;clojure.org
    } else if(I like Microsoft) {
      Use FSharp;fsharp.org;
    } else {
      Use Haskell;haskell.org;
    }
  } else { 
    if(I like Microsoft..) {
      if(I hate C++) {
        if(My computer is ancient..) {
          Use VB6;
        } else {
          Use VB.NET;
        } 
        vbforums.com;
      } else {
        Use CSharp;csharp-station.com;
      }
    } else if(I like Facebook..) {
      Use Hack;hacklang.org;
    } else if(I like Apple..) {
      if(I'm a bit masochist..) {
        Use Objective-C;developer.apple.com;
      } else {
        Use Swift;swift-lang.org;
      }
    } else if(I like Google..) {
      if(But I also like java 
      and javascript..) {
        Use Dart;dartlang.org;
      } else { 
        Use Go;golang.org;
      }
    } else {
      // you can also use Lazarus
      // lazarus.freepascal.org
      Use Delphi;embarcadero.com;
    }
  } 
} else {
  if(I don't want to install a thing..) {
    if(I use linux, mac, or win 10) {
      Use Bash;bash-hackers.org;
    } else {
      Use Javascript;javascript.com;
    }
  } else if(I love spaghetti..) {
    if(I don't care about my future..) {
      // Most likely you will be killed by maintainer that reads your code..
      Use Perl;perl.org;
    } else {
      Use PHP;php.net;
    }
  } else if(I want to make game mods..) {
    Use Lua;lua.org;
  } else if(I like indentations..) {
    Use Python;python.org;
  } else {
    Use Ruby;ruby-lang.org;
  }
}

Aww snaps, I forgot to add Elixir, Julia, and Crystal  -_- oh well.. maybe sometime in the future.

2016-01-20

Kostya's Programming Language Implementation Benchmark

These data taken from https://github.com/kostya/benchmarks with some values removed, I only take the best result, and number of implementation is greater or equal to 3 (Comp, this could be the indicator how easy it's to implement). No further delay, here's the recap:

Implementation Json Brainfuck Mandel Base64 Matmul Havlak Comp Avg Time Avg RAM
Nim Clang 0.12.0 3.37 849.60 3.21 0.70 28.96 1.00 4.67 52.70 3.70 142.30 17.36 907.00 6 10.21 325.55
Rust 1.5.0-nightly 1.35 208.70 5.46 4.90 46.34 4.90 4.25 42.90 4.61 76.90

5 12.40 67.66
Crystal 0.10.0-9d59a34 2.63 1.20 6.97 1.30 48.62 1.30 2.21 85.80 3.83 72.20 15.87 398.10 6 13.36 93.32
Nim Gcc 0.12.0 3.49 903.50 4.52 0.60 50.45 0.90 4.57 52.70 3.76 152.70 17.51 889.10 6 14.05 333.25
Java 1.8.0_45 1.48 518.30 4.94 147.60 55.14 69.90

3.50 136.20

4 16.27 218.00
D 2.068.0 12.42 1,417.10 6.57 1.00 45.29 1.20 6.18 89.10 2.30 71.30 28.90 418.20 6 16.94 332.98
C++ 4.8.2 0.72 1.00 5.08 1.10 56.63 1.10 5.45 65.20

17.72 174.50 5 17.12 48.58
D Ldc 0.15.2-beta1 27.23 919.60 6.61 0.90 43.30 0.90 3.27 44.10 2.01 68.90 25.15 214.90 6 17.93 208.22
D Gdc 1.20.0-232-gc746732 0.34 226.70 8.87 1.00 70.12 1.50 3.16 45.20 2.33 73.00 31.79 197.60 6 19.44 90.83
Go 1.5 4.62 273.10 7.29 1.30 52.56 7.60 13.27 106.20 4.76 73.30 35.34 347.10 6 19.64 134.77
Javascript Node v5.0.0 2.80 829.90 8.74 15.00 92.65 15.80 4.38 628.40 5.88 85.90

5 22.89 315.00
Julia 0.3.11 10.27 2,353.90 9.25 59.00 94.33 56.90 14.76 380.20 31.34 375.80

5 31.99 645.16
Go Gcc 4.9.1 17.64 473.10 13.60 10.00 85.67 10.70 39.56 185.50 3.90 84.50 32.94 365.70 6 32.22 188.25
Python Pypy 4.0.0 with GCC 4.8.4 4.81 1,553.00 13.94 55.40 126.46 64.50 7.32 582.30 7.68 122.60 45.51 625.90 6 34.29 500.62
C# Mono 4.0.1 25.74 3,757.90 18.08 15.40 118.72 13.60 9.01 71.70 15.17 83.60 40.54 270.00 6 37.88 702.03
Javascript Jx 0.10.40 2.73 706.80 17.14 11.00 192.23 12.40 6.97 710.60 5.92 83.80

5 45.00 304.92
Scala 2.11.6 360.95 2,789.00 5.90 116.30 64.37 126.40 10.69 292.50 3.62 136.20 32.18 363.00 6 79.62 637.23
Ruby Jruby 1.7.20 21.98 2,761.10 87.05 124.10

12.65 514.90 416.12 582.40

4 134.45 995.63
Ruby 2.1.2p95 8.23 1,085.50 226.86 8.00

2.73 125.30 338.40 82.80

4 144.06 325.40
Ruby Jruby9K 9.0.0.0.pre2 16.53 2,050.50 160.15 297.20

12.16 530.60 467.59 608.30

4 164.11 871.65
Python3 3.4.3 5.92 1,037.80 480.78 5.50

8.16 47.50



3 164.95 363.60
Python 2.7.6 5.07 1,352.90 452.44 4.90

7.62 52.60 3.08 65.30 396.54 724.00 5 172.95 439.94
Perl 5.18.2 2.68 888.40



3.63 47.90 666.46 604.10

3 224.26 513.47
Ruby Rbx 2.2.10 67.13 4,681.00 472.08 45.00

4.29 30.70 591.70 325.00

4 283.80 1,270.43
Tcl 8.6

262.20 2.70

7.20 66.00 1,066.66 279.90

3 445.35 116.20

For now i'm still betting on Crystal (LLVM-based) and Golang. For next I think I'll try D, maybe with DLangIDE or CoEdit..