Skip to main content

CodeCatchCrasher

0 likes • Feb 11, 2021 • 2 views
JavaScript
Loading...

More JavaScript Posts

test

0 likes • Sep 10, 2023 • 3 views
JavaScript
let test = 1;

insertion sort

0 likes • Nov 19, 2022 • 0 views
JavaScript
const insertionSort = arr =>
arr.reduce((acc, x) => {
if (!acc.length) return [x];
acc.some((y, j) => {
if (x <= y) {
acc.splice(j, 0, x);
return true;
}
if (x > y && j === acc.length - 1) {
acc.splice(j + 1, 0, x);
return true;
}
return false;
});
return acc;
}, []);
insertionSort([6, 3, 4, 1]); // [1, 3, 4, 6]

typewriter-effect in Vanilla JS and React

CHS
0 likes • Jan 25, 2023 • 5 views
JavaScript
// Vanilla JS Solution:
var app = document.getElementById('app');
var typewriter = new Typewriter(app, { loop: true });
typewriter
.typeString("I'm John and I'm a super cool web developer")
.pauseFor(3000)
.deleteChars(13) // "web developer" = 13 characters
.typeString("person to talk with!") // Will display "I'm John and I'm a super cool person to talk with!"
.start();
// React Solution:
import Typewriter from 'typewriter-effect';
<Typewriter
options={{ loop: true }}
onInit={typewriter => {
typewriter
.typeString("I'm John and I'm a super cool web developer")
.pauseFor(3000)
.deleteChars(13) // "web developer" = 13 characters
.typeString("person to talk with!") // Will display "I'm John and I'm a super cool person to talk with!"
.start();
}}
/>

Sequential Queue

0 likes • Feb 6, 2021 • 2 views
JavaScript
class SequentialQueue{ //if you want it to go backwards, too bad
next(){
return this.i++;
}
constructor(start = 0){
this.i = start;
}
}
const que = new SequentialQueue(0);
for(let i = 0; i < 10; i++){
console.log(que.next());
}

kNearestNeighbors

0 likes • Nov 19, 2022 • 5 views
JavaScript
const kNearestNeighbors = (data, labels, point, k = 3) => {
const kNearest = data
.map((el, i) => ({
dist: Math.hypot(...Object.keys(el).map(key => point[key] - el[key])),
label: labels[i]
}))
.sort((a, b) => a.dist - b.dist)
.slice(0, k);
return kNearest.reduce(
(acc, { label }, i) => {
acc.classCounts[label] =
Object.keys(acc.classCounts).indexOf(label) !== -1
? acc.classCounts[label] + 1
: 1;
if (acc.classCounts[label] > acc.topClassCount) {
acc.topClassCount = acc.classCounts[label];
acc.topClass = label;
}
return acc;
},
{
classCounts: {},
topClass: kNearest[0].label,
topClassCount: 0
}
).topClass;
};
const data = [[0, 0], [0, 1], [1, 3], [2, 0]];
const labels = [0, 1, 1, 0];
kNearestNeighbors(data, labels, [1, 2], 2); // 1
kNearestNeighbors(data, labels, [1, 0], 2); // 0

binary search

0 likes • Nov 19, 2022 • 1 view
JavaScript
const binarySearch = (arr, item) => {
let l = 0,
r = arr.length - 1;
while (l <= r) {
const mid = Math.floor((l + r) / 2);
const guess = arr[mid];
if (guess === item) return mid;
if (guess > item) r = mid - 1;
else l = mid + 1;
}
return -1;
};
binarySearch([1, 2, 3, 4, 5], 1); // 0
binarySearch([1, 2, 3, 4, 5], 5); // 4
binarySearch([1, 2, 3, 4, 5], 6); // -1