Search This Blog

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

Enable code syntax highlighting in blogger site using highlightjs

  • Template -> Edit HTML
  • Insert the following inside <head> tag:
        
        <!-- BEGIN: Syntax Highlighting with highlight.js -->
        <link crossorigin='anonymous' href='https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/agate.min.css' integrity='sha512-wI7oXtzNHj/bqfLA3P6x3XYbcwzsnIKaPLfjjX8ZAXhc65+kSI6sh8gLOOByOKImokAjHUQR0xAJQ/xZTzwuOA==' referrerpolicy='no-referrer' rel='stylesheet'/>
        <script crossorigin='anonymous' integrity='sha512-bgHRAiTjGrzHzLyKOnpFvaEpGzJet3z4tZnXGjpsCcqOnAH6VGUx9frc5bcIhKTVLEiCO6vEhNAgx5jtLUYrfA==' referrerpolicy='no-referrer' src='https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js'/>
        <script>hljs.highlightAll();</script>
        <!-- END: Syntax Highlighting with highlight.js -->
        <!-- BEGIN: CSS for code in pre and code -->
        <style type='text/css'>
            pre {
                font-family: monospace;
                font-size: 1 em;
                background: #333;
                color: #33cc33;
                tab-size: 4;
                padding: 5px;
                border: 1px dotted grey;
                border-radius: 5px;
                line-height: 2.0;
                overflow-x: auto;
                white-space: pre-wrap;
            }
    
            code {
                white-space: pre-wrap;
                overflow-x: scroll;    
                font-family: monospace;
                font-size: 1em;
            }
        </style>
        <!-- END: CSS for code in pre and code -->
        
        
  • Click save icon to save the template
  • Use it in your blog post:
    <pre><code class="language-html">...</code></pre>



See also

Javascript: sort string array alphabetically

localeCompare() method can be used:
const array = ['b', 'd', 'c', 'a'];
array.sort((a,b)=>a.localeCompare(b));



see also

Javascript: remove duplicated values from array

Get distinct values from Array
let array = ['aaa', 'bbb', 'ccc', 'bbb', 'ddd'];
console.log(array);

array = Array.from(new Set(array));
console.log(array);



Get distinct values from Map
const map = new Map<string, number>();
map.set('foo', 1);
map.set('bar', 2);
map.set'zoo', 1);
const distinctValues = Array.from(new Set(map.values()));



see also

Add Inverse Grayscale colour table to Papaya Viewer

Papaya viewer is a pure JavaScript medical research image viewer. You can add custom colour table by modifying its source code and rebuild. See the steps below:
  • Check out Papaya source code
    git clone https://github.com/rii-mango/Papaya.git
  • Modify src/js/viewer/colortable.js
    // insert after line 44:
    papaya.viewer.ColorTable.TABLE_INVERSE_GRAYSCALE = {"name": "Inverse Grayscale", "data": [[0, 1, 1, 1], [1, 0, 0, 0]],
         "gradation": true};
    
    // insert after line 94:
    papaya.viewer.ColorTable.TABLE_ALL = [
        papaya.viewer.ColorTable.TABLE_GRAYSCALE,
        papaya.viewer.ColorTable.TABLE_INVERSE_GRAYSCALE,
        papaya.viewer.ColorTable.TABLE_SPECTRUM,
        papaya.viewer.ColorTable.TABLE_FIRE,
        papaya.viewer.ColorTable.TABLE_HOTANDCOLD,
        papaya.viewer.ColorTable.TABLE_GOLD,
        papaya.viewer.ColorTable.TABLE_RED2YELLOW,
        papaya.viewer.ColorTable.TABLE_BLUE2GREEN,
        papaya.viewer.ColorTable.TABLE_RED2WHITE,
        papaya.viewer.ColorTable.TABLE_GREEN2WHITE,
        papaya.viewer.ColorTable.TABLE_BLUE2WHITE
    ];
    	
  • Build using papaya-builder.sh
    ./papaya-builder.sh
    The result papaya.js and papaya.css will be in build/ directory.



see also

Javascript: access object property

const obj = { name: 'John Foo', email: 'john.foo@aaa.com' };

let prop = 'name';
console.log(obj[prop]); // 'John Foo'

prop = 'email';
console.log(obj[prop]); // 'john.foo@aaa.com'



See also

MUI DataGrid Column for nested object

const data = [ 
               { company: 'AAA', contact: { name: 'John Doe', email: 'john.doe@aaa.com } },
               { company: 'BBB', contact: { name: 'Mike Boh', email: 'mike.boh@bbb.com } }
             ];


const columnDefns=[
            {
                field: 'company',
                headerName: 'Company',
            },
            {
                field: 'contact',
                headerName: 'Contact',
                valueFormatter: (params) => params.contact.name
            }
            ];



see also

Javascript: number to string

  • Javascript/Typescript:
    const n = 1;
    const s1 = '' + 1;
    console.log(typeof s1); // string
    console.log(s1); // '1'
    
    const s2 = String(n);
    console.log(typeof s2); // string
    console.log(s2); // '1'
  • Typescript:
    const n = 1;
    const s1 = <string><any>n;
    console.log(typeof s1); // string
    console.log(s1); // '1'
    
    const s2 = n as any as string;
    console.log(typeof s2); // string
    console.log(s2); // '1'



see also

Javascript: check variable type

const a = 1;
const b = '2';

console.log(typeof a); // 'number'
console.log(typeof a === 'number'); // true

console.log(typeof b); // 'string'
console.log(typeof b === 'string'); // true

Javascript: find all matches

const regex = /([^\/]+):/g;
const s = 'MMM:mmm/AAA:aaa/BBB:bbb/ccc';

let m;
while(m = regex.exec(s)) {
	console.log(m[0], m[1]);
}



see also

Javascript: create a object property from a variable

  • Option 1:
      const name = 'n';
      let obj = {};
      obj[name]=1;
      
  • Option 2(ES6):
      const name = 'n';
      let obj = { [name] : 1}
      

Styling React App with Emotion

  • Install Emotion packages into your React App by running the command inside the React project directory:
    npm install --save @emotion/react @emotion/styled
  • Add following to tsconfig.json
    {
      "compilerOptions": {
        ...
        "jsx": "react-jsx",
        "jsxImportSource": "@emotion/react",
        ...
      }
    }
  • At the top of your .tsx file, insert line:
    /** @jsxImportSource @emotion/react */



see also

Date.parse() behaves different in Firefox compared with Chrome for 'dd-MMM-yyyy'

Date.parse('12-Jan-2022'); works fine in Chrome/Edge, however, Firefox returns wrong date.


To parse the string in Firefox, I wrote my own parser in Typescript:
export function parseDate(ds: string): Date  {
    const regexDateOnly = /^\d{1,2}-[ADFJMNOS]{1}[abceglnoprtuvy]{2}-\d{4}$/g;
    const regexDateTime = /^\d{1,2}-[ADFJMNOS]{1}[abceglnoprtuvy]{2}-\d{4} \d{2}:\d{2}:\d{2}$/g;
    const regexDateTimeMilliSecs = /^\d{1,2}-[ADFJMNOS]{1}[abceglnoprtuvy]{2}-\d{4} \d{2}:\d{2}:\d{2}\.\d{3}$/g;
    let datePart = '';
    let timePart = '';
    let millisPart = '';
    if (regexDateTimeMilliSecs.test(ds)) {
        const parts1 = ds.split(' ');
        const parts2 = parts1[1].split('.');
        datePart = parts1[0];
        timePart = parts2[0];
        millisPart = parts2[1];
    } else if (regexDateTime.test(ds)) {
        const parts = ds.split(' ');
        datePart = parts[0];
        timePart = parts[1];
    } else if (regexDateOnly.test(ds)) {
        datePart = ds;
    } else {
        throw new Error(`Failed to parse date: ${ds}`)
    }
    let year = 1970, month = 0, day = 1, hour = 0, minute = 0, second = 0, millisecs = 0;
    if (datePart) {
        const parts = datePart.split('-');
        day = parseInt(parts[0]);
        switch (parts[1].toLowerCase()) {
            case 'jan':
                month = 0;
                break;
            case 'feb':
                month = 1;
                break;
            case 'mar':
                month = 2;
                break;
            case 'apr':
                month = 3;
                break;
            case 'may':
                month = 4;
                break;
            case 'jun':
                month = 5;
                break;
            case 'jul':
                month = 6;
                break;
            case 'aug':
                month = 7;
                break;
            case 'sep':
                month = 8;
                break;
            case 'oct':
                month = 9;
                break;
            case 'nov':
                month = 10;
                break;
            case 'dec':
                month = 11;
                break;
            default:
                break;
        }
        year = parseInt(parts[2]);
    }
    if (timePart) {
        const parts = timePart.split(':');
        hour = parseInt(parts[0]);
        minute = parseInt(parts[1]);
        second = parseInt(parts[2]);
    }
    if (millisPart) {
        millisecs = parseInt(millisPart);
    }
    return new Date(year, month, day, hour, minute, second, millisecs);
}


see also

Setup Svelte Material UI

  1. Install svelte-preprocess
    npm install -D svelte-preprocess
  2. Install any Svelte Material UI comonent:
    npm install --save-dev @smui/button
    Note: you need to install at least one component otherwise you cannot compile the theme css.
  3. Install smui-theme and create a template at src/theme
    npm install -D smui-theme
    npx smui-theme template src/theme
  4. Add following script to scripts section of package.json
    "prepare": "smui-theme compile public/build/smui.css -i src/theme"
  5. Compile the css from smui-theme template:
    npm run prepare
    It should create public/build/smui.css
  6. Add the compiled css to public/index.html file:
    <link rel='stylesheet' href='/build/smui.css'>
  7. Add Material Fonts to public/index.html
    <link
    rel="stylesheet"
    href="https://fonts.googleapis.com/icon?family=Material+Icons"
    />
    <!-- Roboto -->
    <link
    rel="stylesheet"
    href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,600,700"
    />
    <!-- Roboto Mono -->
    <link
    rel="stylesheet"
    href="https://fonts.googleapis.com/css?family=Roboto+Mono"
    />

Set up http proxy for Svelte web app using rollup-plugin-dev

  • Install rollup-plugin-dev:
    npm install -D rollup-plugin-dev
  • Modify rollup.config.js:
    import dev from 'rollup-plugin-dev';
    ... ...
    export default {
    	... ...
        plugins: [
        	... ...
            !production && dev({
            	host: 'localhost',
    			port: 5000,
    			dirs: ['public'],
    			proxy: [{ from: '/__mflux_svc__', to: 'http://localhost:8086' }]
    		}),
        
        // !production && serve(),
        ... ...
        ]
    }
    	

see also

Create a Svelte Typescript app from rollup template

  1. Initialize Svelte Web App:
    npx degit sveltejs/template svelte-ts-app
    cd svelte-ts-app
    node scripts/setupTypeScript.js
    npm install
    
  2. [Optional] Install rollup-plugin-dev to enable http proxy
  3. [Optional] Setup Svelte Material UI components
  4. Starts rollup dev mode:
    npm run dev
  5. Building and running in production mode:
    npm run dev
    npm run start
      

see also