Skip to main content

typewriter-effect in Vanilla JS and React

Jan 25, 2023CHS
Loading...

More JavaScript Posts

Mongoose DB Connection

Mar 11, 2021CHS

0 likes • 0 views

require("dotenv").config();
const mongoose = require("mongoose");
const db = process.env.MONGO_URI;
const connectDB = async () => {
try {
await mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
});
console.log("MongoDB Connected");
} catch (err) {
console.error(err.message);
}
};
module.exports = connectDB;

luhnCheck implementation

Nov 19, 2022CodeCatch

0 likes • 1 view

const luhnCheck = num => {
let arr = (num + '')
.split('')
.reverse()
.map(x => parseInt(x));
let lastDigit = arr.splice(0, 1)[0];
let sum = arr.reduce(
(acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val *= 2) > 9 ? val - 9 : val)),
0
);
sum += lastDigit;
return sum % 10 === 0;
};
luhnCheck('4485275742308327'); // true
luhnCheck(6011329933655299); // true
luhnCheck(123456789); // false

Truncate to fixed decimal

Nov 19, 2022CodeCatch

0 likes • 0 views

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1); // 25.1
toFixed(25.198726354, 2); // 25.19
toFixed(25.198726354, 3); // 25.198
toFixed(25.198726354, 4); // 25.1987
toFixed(25.198726354, 5); // 25.19872
toFixed(25.198726354, 6); // 25.198726

bucket sort

Nov 19, 2022CodeCatch

0 likes • 0 views

const bucketSort = (arr, size = 5) => {
const min = Math.min(...arr);
const max = Math.max(...arr);
const buckets = Array.from(
{ length: Math.floor((max - min) / size) + 1 },
() => []
);
arr.forEach(val => {
buckets[Math.floor((val - min) / size)].push(val);
});
return buckets.reduce((acc, b) => [...acc, ...b.sort((a, b) => a - b)], []);
};
bucketSort([6, 3, 4, 1]); // [1, 3, 4, 6]

Composing components

Nov 19, 2022CodeCatch

0 likes • 0 views

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);

euclidean distance

Nov 19, 2022CodeCatch

0 likes • 3 views

const euclideanDistance = (a, b) =>
Math.hypot(...Object.keys(a).map(k => b[k] - a[k]));
euclideanDistance([1, 1], [2, 3]); // ~2.2361
euclideanDistance([1, 1, 1], [2, 3, 2]); // ~2.4495