0 likes • Nov 18, 2022
JavaScript

## More JavaScript Posts

### Rings and Rods

CodeCatch
0 likes • Nov 19, 2022
JavaScript
```// There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.
// You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:
// The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').// The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').// For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.
// Return the number of rods that have all three colors of rings on them.

let rings = "B0B6G0R6R0R6G9";var countPoints = function(rings) {        let sum = 0;    	// Always 10 Rods    for (let i = 0; i < 10; i++) {        if (rings.includes(`B\${i}`) && rings.includes(`G\${i}`) && rings.includes(`R\${i}`)) {            sum+=1;        }    }        return sum;    };
console.log(countPoints(rings));```

### Ticking clock

CodeCatch
0 likes • Nov 19, 2022
JavaScript
```function Clock(props) {  return (    <div>      <h1>Hello, world!</h1>      <h2>It is {props.date.toLocaleTimeString()}.</h2>    </div>  );}
function tick() {  ReactDOM.render(    <Clock date={new Date()} />,    document.getElementById('root')  );}
setInterval(tick, 1000);```
```const jwt = require("jsonwebtoken");
const authToken = (req, res, next) => {	const token = req.headers["x-auth-token"];
try {	req.user = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);
next();	} catch (err) {	console.log(err.message);	res.status(401).json({ msg: "Error authenticating token" });	}};
module.exports = authToken;```

### Flatten an array

CodeCatch
0 likes • Nov 19, 2022
JavaScript
```const flat = arr => [].concat.apply([], arr.map(a => Array.isArray(a) ? flat(a) : a));// Orconst flat = arr => arr.reduce((a, b) => Array.isArray(b) ? [...a, ...flat(b)] : [...a, b], []);
// Or// See the browser compatibility at https://caniuse.com/#feat=array-flatconst flat = arr => arr.flat();
// Exampleflat(['cat', ['lion', 'tiger']]);   // ['cat', 'lion', 'tiger']```
```// promisify(f, true) to get array of resultsfunction promisify(f, manyArgs = false) {  return function (...args) {    return new Promise((resolve, reject) => {      function callback(err, ...results) { // our custom callback for f        if (err) {          reject(err);        } else {          // resolve with all callback results if manyArgs is specified          resolve(manyArgs ? results : results[0]);        }      }
args.push(callback);
f.call(this, ...args);    });  };}
// usage:f = promisify(f, true);f(...).then(arrayOfResults => ..., err => ...);```
```"use strict";const nodemailer = require("nodemailer");
// async..await is not allowed in global scope, must use a wrapperasync function main() {  // Generate test SMTP service account from ethereal.email  // Only needed if you don't have a real mail account for testing  let testAccount = await nodemailer.createTestAccount();
// create reusable transporter object using the default SMTP transport  let transporter = nodemailer.createTransport({    host: "smtp.ethereal.email",    port: 587,    secure: false, // true for 465, false for other ports    auth: {      user: testAccount.user, // generated ethereal user      pass: testAccount.pass, // generated ethereal password    },  });
// send mail with defined transport object  let info = await transporter.sendMail({    from: '"Fred Foo 👻" <[email protected]>', // sender address    to: "[email protected], [email protected]", // list of receivers    subject: "Hello ✔", // Subject line    text: "Hello world?", // plain text body    html: "<b>Hello world?</b>", // html body  });
console.log("Message sent: %s", info.messageId);  // Message sent: <[email protected]>
// Preview only available when sending through an Ethereal account  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...}
main().catch(console.error);```