Javascript tips

Aug 5, 04:30 AM

Javascript usage

1: use const when in a for loop (makes more readable
for (const myRow of Object
2: start using querySelector and querySelectorAll
document.querySelectorAll('tag#.id or class').forEach( element =>  { console.log(element); } );
3: when querying for selector, use the data attribute (notice [data-XXX=]):
document.getElementById('mark').querySelectorAll('smart-input[data-zyx="myVal"] input'))
4: use setAttribute() and getAttribute() for data & value in any element
     // stop using  element.dataset.thisDataValue
    // use   element.getAttribute('data-this-data-value');
5: Use Boolean() to test null, zero, blank,etc
if  ( Boolean(myValue) == true ) {

6: to use a variable value for an object tag, enclose the variable name inside of square brackets:

    let myVar = 'mark';
    let newObj = {  [myVar] : 'this value' } ;
7. Destructuring – there is a fast way to extract out an object element:
let  myVar  = thisObj.myVar;
let  {myVar} = thisObj     ;   // same as above but less typing.
8. object mapping:
// Creates an array of objects with unique "name" property values.
let uniqueObjArray = [
    ...new Map(myObjArray.map(  item => {   
                    const { keyToBeSkipped, anotherKeyToSkip, ...remainingItems} = item ; 
                    return  [ JSON.stringify(remainingItems) , remainingItems]  
              })).values(),
];
console.info( uniqueObjArray);
https://yagisanatode.com/get-a-unique-list-of-objects-in-an-array-of-object-in-javascript/
https://plainenglish.io/blog/how-to-get-distinct-values-from-an-array-of-objects-in-javascript
https://www.geeksforgeeks.org/how-to-remove-a-key-from-javascript-object/

9. to manipulate a stylesheet:
const stylesheet = new CSSStyleSheet();  
stylesheet.replaceSync('body { background-color:    orange; }'); 
document.adoptedStyleSheets = [stylesheet];
10. to extract out a value from an object, use object(DOT)find:
const	frequency	 =	values[0]		;								;
const	frequencyListAutoIncr
    =	frequencyListObj.find( item => item.frequency == values[0]).frequencyListAutoIncr	;

11: debounce – see separate article on debounce

12: every() The every() method of Array instances tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.and why it returns true for an empty array

const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// Expected output: true

99: when leaving a promise, create a fake error then call it:

class ExitEarly extends Error {
    constructor(message) {
        super(message);
        this.name = “ExitEarly”;
    }
}

firstPromise.then(result => {
    if (/* time to exit early for whatever reason */) {
        throw new ExitEarly(‘Exiting after firstPromise’);
    }
    return secondPromise(result);
})
Mark Edwards

,

---

two styles for feathers hooks

Jul 24, 11:27 AM

https://knexjs.org/guide/query-builder.html#knex

module.exports = (options = {}) => {
  return async context => {
        context.params.query = {                        // added by mark
          ...context.params.query,                      // added by mark
          $select: ['clientStimwordNotes']              // added by mark
        }                                               // added by mark
    return context;
  };
};
to completely rewrite the query:
module.exports = (options = {}) => {
  return async context => {

        const query = context.service.createQuery(context.params);
        const knexClient =   context.app.get(‘knexClient’) ;
        query   .clear(‘select’)
                .select  (   ‘col_4’  
                         ,  { ‘my Column’    ,   `col0’  }
                         ,  knexClient.raw(“CONCAT AS col1_2”)
                          )
                .distinct()
                .orderBy(‘languageNormsName’)
                ;
        context.params.knex = query

    return context;
  };
};
notice the THREE different styles of selection.
Mark Edwards

,

---

Change LastPass logout time

Jul 18, 04:57 PM

1 – RIGHT-CLICK LastPass icon (RED square three white dots in the chrome extensions toolbar)

2 – select options (third one down)

3 – General tab (if not already selected)

4 – Log out after this many minutes of inactivity 60 (make sure its checked!)

5 – SAVE button lower right

Mark Edwards

,

---

moving a WP multiuser website to single-user website

Jul 4, 06:08 AM

0) etc.hosts – add ip ## & domain name

1) create a new google-vm or virtualbox-vm with apache, php & mariadb

2) echo ‘‘ > /var/www/html/phpinfo.php ;

3) http://domainName/phpinfo.php — check if page loads

4) create mariadb user:
    CREATE USER ‘WpUser’@‘localhost’ IDENTIFIED BY ‘WpPassword’;

    GRANT ALL ON `WpDb`.* TO ‘WpUser’@‘localhost’	
    IDENTIFIED BY ‘WpPassword’ 							
    WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 
    MAX_USER_CONNECTIONS 0	;

    DROP DATABASE IF EXISTS `wpDb` ; 
   CREATE DATABASE IF NOT EXISTS `wpDb` 			;

    GRANT ALL PRIVILEGES ON `wpDb`.* TO ‘wpUser’@‘localhost’	;

    # test:  mariadb  —host=localhost —user=wpUser  —password=wpPassword  wpDb    ;   

5) wget https://wordpress.org/latest.tar.gz ;

6) gzip —decompress and tar into position
6a) rm -f *.php readme.html ./wc-content/ ./wp-includes/ ./wp-admin/ ;
6b) chown -R apache:apache /var/www/html

7) create new WP site using db info from step two

8) install prime-mover plugin

9) prime-mover import data

10) EXPORT new website using something like all-in-one migration

shared-hosting-cpanel:

1) create LAMP
2) manually install WP
3) install prime-mover plugin
4) import from previous step

EasyWP import: 1) create an EasyWP website

2) use all-in-one to IMPORT the export from step 10.

3) delete google-analytics plugin, some sort of conflict.

Mark Edwards

,

---

running a javascript "module" in the console

Jun 6, 06:30 AM

in this example i use waveSurfer

step one: visit the webpage: about:blank

step two: enter the following code in the console:

var WaveSurfer = null;   // required for creating a global variable.
let script		        = document.createElement('script')		;
script.type		= 'module'				             ;
script.innerText	= `
    import ws from 'https://unpkg.com/wavesurfer.js@beta'; 
    WaveSurfer=ws;
`;
let script		= document.createElement('script')		;
script.type		= 'module'				;
Object.assign(script, 	{innerText } );  // fancy way of assigning a key:value to this object
document.head.appendChild(script);
step three: after waiting a half-second, enter the following code in the console:
const wavesurfer = WaveSurfer.create({
  'container': document.body,
  waveColor: '#4F4A85',
  progressColor: '#383351',
  url: 'https://wavesurfer-js.org//wavesurfer-code/examples/audio/audio.wav',
})
wavesurfer.once('interaction', () => {
  wavesurfer.play()
})
wavesurfer shoudl appear in the browser window.

timeline example:

var WaveSurfer = null;        // required for creating a global variable.
var TimelinePlugin = null;    // required for creating a global variable.
let innerText = `
    import ws from ‘https://unpkg.com/wavesurfer.js@beta’; 
    WaveSurfer = ws;
    import tlPlugin from ‘https://unpkg.com/wavesurfer.js@beta/dist/plugins/timeline.js’;
    TimelinePlugin = tlPlugin;
`;

let script		= document.createElement(‘script’)		;
script.type		= ‘module’				;
Object.assign(script,  { innerText } ); // fancy way of assigning this object a value!
document.head.appendChild(script);
const wavesurfer = WaveSurfer.create({
  ‘container’: document.body,
  waveColor: ‘#4F4A85’,
  progressColor: ‘#383351’,
  url: ‘https://wavesurfer-js.org//wavesurfer-code/examples/audio/audio.wav’,
})
wavesurfer.registerPlugin(TimelinePlugin.create());

wavesurfer.once(‘interaction’, () => {
  wavesurfer.play()
})
Mark Edwards

,

---

« Older Newer »

Manage