Skip to main content

Get timezone as a string

0 likes • Nov 19, 2022 • 0 views
JavaScript
Loading...

More JavaScript Posts

React - Lifting State

CHS
0 likes • Jan 25, 2023 • 2 views
JavaScript
export const Main = () => {
const [title, setTitle] = useState('');
return (
<ChildComponent
title={title}
onChange={e => setTitle(e.target.value)}
/>
);
};
export const ChildComponent = ({ title, onChange }) => {
return (
<Box component="form" onSubmit={() => {}} noValidate mt={5}>
<TextField
fullWidth
id="title"
label="Title"
name="title"
autoComplete="title"
autoFocus
color="primary"
variant="filled"
InputLabelProps={{ shrink: true }}
value={title}
onChange={onChange}
/>
</Box>
);
};

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

getSelectedText

0 likes • Nov 18, 2022 • 0 views
JavaScript
// Get the text that the user has selected
const getSelectedText = () => window.getSelection().toString();
getSelectedText();

Date Time Testing

0 likes • Nov 18, 2022 • 1 view
JavaScript
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

Subsets of an array

0 likes • Nov 19, 2022 • 1 view
JavaScript
const getSubsets = arr => arr.reduce((prev, curr) => prev.concat(prev.map(k => k.concat(curr))), [[]]);
// Examples
getSubsets([1, 2]); // [[], [1], [2], [1, 2]]
getSubsets([1, 2, 3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

heap sort

0 likes • Nov 19, 2022 • 0 views
JavaScript
const heapsort = arr => {
const a = [...arr];
let l = a.length;
const heapify = (a, i) => {
const left = 2 * i + 1;
const right = 2 * i + 2;
let max = i;
if (left < l && a[left] > a[max]) max = left;
if (right < l && a[right] > a[max]) max = right;
if (max !== i) {
[a[max], a[i]] = [a[i], a[max]];
heapify(a, max);
}
};
for (let i = Math.floor(l / 2); i >= 0; i -= 1) heapify(a, i);
for (i = a.length - 1; i > 0; i--) {
[a[0], a[i]] = [a[i], a[0]];
l--;
heapify(a, 0);
}
return a;
};
heapsort([6, 3, 4, 1]); // [1, 3, 4, 6]