javascript supplementary notes


1. converting between strings and arrays

u = 'pineapple,orange,mongo,grape,guava,banana,cherry,strawberry'
u.substr(5,8)
v = u.split('')
v.slice(5,8)
w = u.split(',')
x = []
for (i=0; i<w.length; ++i) { x[i] = w[i].split(''); }
for (i=0; i<x.length; ++i) { y[i] = x[i].join(''); }
z = y.join(',')

2. processing a json file

First save this json file as config.json . Then in nodejs:

const fs = require('fs');
let rawdata = fs.readFileSync('config.json');

let config = JSON.parse(rawdata);
config;
let config2 = config; // save a backup for later use
config['plotly']['layout'];
// Q: try to change its 'title' attribute to 'natural satellites'
JSON.stringify(config, null, 2);
console.log(JSON.stringify(config, null, 2));
Object.keys(config);
Object.keys(config['plotly']['layout']);
delete config['plotly']['maintrace']['color'];
// Two ways to iterate over an object:
data = config['plotly']['maintrace']
Object.keys(data)
for (k of Object.keys(data)) { console.log(k, ' ==> ', data[k]); }
for (k in data) { console.log(k, ' ==> ', data[k]); }
Object.entries(data)
for ([k, v] of Object.entries(data)) { console.log(k, ' ==> ', v); }

config2;
console.log(JSON.stringify(config2, null, 2));
// what happened?

3. regex

const fs = require('fs');
let rawdata = fs.readFileSync('access.log', 'UTF-8');
rawdata = rawdata.split('\n');

let pat1 = new RegExp(/:([0-9][0-9]:[0-9][0-9]):/);
for (let line of rawdata) {
    matches = pat1.exec(line);
    if (matches) {
	console.log('A: ' + matches[1]);
    }
    matches = line.match(/:([0-9][0-9]:[0-9][0-9]):/);
    if (matches) {
	console.log('B: ' + matches[1]);
    }
}

4. callbacks/lambda/anonymous/arrow functions

Review: slope of a straight line and tangent line.

function f1(x) { return x*x; }
function diff(f, x) { return (f(x+1e-5)-f(x))/1e-5; }
diff(f1, 5);
diff(f1, 7);
Math.sqrt(2);
Math.sqrt(3);
diff(Math.sqrt, 2);
diff(Math.sqrt, 9);
f2 = x => x*x;
diff(f2, 5);
diff(f2, 7);
diff(function(x) { return x*x; }, 5);
diff( x=>x*x, 5 );

fruits = 'pineapple,orange,mongo,grape,guava,banana,cherry,strawberry'.split(',');
fruits.forEach(function(x) { console.log(x); });
fruits.map(function(x) { return x[0] + x[x.length-1]; });
// Q: Print the same 2-char strings using forEach() instead
// Q: What's the difference between forEach() and map()?
fruits.filter( x => x.length==6 );

primes = [ 17, 3, 2, 5, 19, 7, 13, 11 ];
primes.reduce( (s,x)=>s+x, 0 );
primes.reduce( (s,x)=>s*x, 1 );
// Q: Find the largest number in the list using reduce.
// You may need Infinity and "if ... else ..." statement.
// How short can you make your program?

// Q: Write a piece of code to generate:
// [ 'ieae', 'oae', 'oo', 'ae', 'uaa', 'aaa', 'e', 'ae' ]
// making use of map(), filter(), split(), join(), and includes().

(back to course homepage)