Skip to content

Instantly share code, notes, and snippets.

@bluenex
Last active September 27, 2023 06:51
Show Gist options
  • Save bluenex/de550b9a8cf2f1a50177d3ebce169514 to your computer and use it in GitHub Desktop.
Save bluenex/de550b9a8cf2f1a50177d3ebce169514 to your computer and use it in GitHub Desktop.
A collection of snippets
interface ObjectWithTimestamp {
timestamp: number;
}
function findClosestTimestampPair(
arr1: ObjectWithTimestamp[],
arr2: ObjectWithTimestamp[]
): [ObjectWithTimestamp, ObjectWithTimestamp][] | [] {
arr1.sort((a, b) => a.timestamp - b.timestamp);
arr2.sort((a, b) => a.timestamp - b.timestamp);
let i = 0;
let j = 0;
let minDiff = Infinity;
let closestPair: [ObjectWithTimestamp, ObjectWithTimestamp][] = [];
while (i < arr1.length && j < arr2.length) {
const diff = Math.abs(arr1[i].timestamp - arr2[j].timestamp);
if (diff < minDiff) {
minDiff = diff;
closestPair = [[arr1[i], arr2[j]]];
} else if (diff === minDiff) {
closestPair.push([arr1[i], arr2[j]]);
}
if (arr1[i].timestamp < arr2[j].timestamp) {
i++;
} else {
j++;
}
}
if (minDiff >= Math.abs(arr1[arr1.length - 1].timestamp - arr2[0].timestamp)) {
return [];
}
return closestPair;
}
var a = [
{ name: "a", timestamp: new Date("2022-12-01T00:00:00Z").getTime() },
{ name: "b", timestamp: new Date("2023-09-01T00:00:00Z").getTime() },
{ name: "c", timestamp: new Date("2023-03-01T00:00:00Z").getTime() },
]
var x = [
{ name: "x", timestamp: new Date("2022-12-01T01:00:00Z").getTime() },
{ name: "y", timestamp: new Date("2023-03-01T01:00:00Z").getTime() },
]
console.log(findClosestTimestampPair(a, x));
function getRandomString(seed: string, length: number = 8) {
let hash = 0
for (let i = 0; i < seed.length; i++) {
hash = (hash << 5) - hash + seed.charCodeAt(i)
}
const characterSets = [
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz',
'0123456789',
]
let randomResult = ''
for (let i = 0; i < 8; i++) {
const setIndex = Math.abs(hash + i) % characterSets.length
const characterSet = characterSets[setIndex]
const randomIndex = Math.abs(hash + i) % characterSet.length
randomResult += characterSet.charAt(randomIndex)
}
return randomResult
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment