Skip to main content

deep merge objects

Nov 19, 2022CodeCatch
Loading...

More JavaScript Posts

arithmetic progression

Nov 19, 2022CodeCatch

0 likes • 0 views

const arithmeticProgression = (n, lim) =>
Array.from({ length: Math.ceil(lim / n) }, (_, i) => (i + 1) * n );
arithmeticProgression(5, 25); // [5, 10, 15, 20, 25]

Clone an array

Nov 19, 2022CodeCatch

0 likes • 1 view

// `arr` is an array
const clone = arr => arr.slice(0);
// Or
const clone = arr => [...arr];
// Or
const clone = arr => Array.from(arr);
// Or
const clone = arr => arr.map(x => x);
// Or
const clone = arr => JSON.parse(JSON.stringify(arr));
// Or
const clone = arr => arr.concat([]);

drag and drop uploader

Nov 18, 2022AustinLeath

0 likes • 0 views

const dragAndDropDiv = editor.container;
dragAndDropDiv.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
dragAndDropDiv.addEventListener("drop",function(e){
// Prevent default behavior (Prevent file from being opened)
e.stopPropagation();
e.preventDefault();
const files = e.dataTransfer.items; // Array of all files
console.assert(files.length >= 1);
if (files[0].kind === 'file') {
var file = e.dataTransfer.items[0].getAsFile();
const fileSize = file.size;
const fileName = file.name;
const fileMimeType = file.type;
reader = new FileReader();
reader.onloadend = function(){
editor.setValue(reader.result);
}
reader.readAsText(file);
}else{
//Maybe handle if text is dropped
console.log(files[0].kind);
}
});

levenshtein distance

Nov 19, 2022CodeCatch

0 likes • 1 view

const levenshteinDistance = (s, t) => {
if (!s.length) return t.length;
if (!t.length) return s.length;
const arr = [];
for (let i = 0; i <= t.length; i++) {
arr[i] = [i];
for (let j = 1; j <= s.length; j++) {
arr[i][j] =
i === 0
? j
: Math.min(
arr[i - 1][j] + 1,
arr[i][j - 1] + 1,
arr[i - 1][j - 1] + (s[j - 1] === t[i - 1] ? 0 : 1)
);
}
}
return arr[t.length][s.length];
};
levenshteinDistance('duck', 'dark'); // 2

greatest common denominator

Nov 19, 2022CodeCatch

0 likes • 0 views

const gcd = (...arr) => {
const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
return [...arr].reduce((a, b) => _gcd(a, b));
};
gcd(8, 36); // 4
gcd(...[12, 8, 32]); // 4

MongoDB Connection

Oct 15, 2022CodeCatch

3 likes • 4 views

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});