Last active
April 13, 2024 17:51
-
-
Save mary-ext/6c5f3c6ab00bf9a5523645e43e61a51c to your computer and use it in GitHub Desktop.
Convert Bluesky's datetime search to local time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/golang/go/blob/519f6a00e4dabb871eadaefc8ac295c09fd9b56f/src/strings/strings.go#L377-L425 | |
const fieldsfunc = (str: string, fn: (rune: number) => boolean): string[] => { | |
const slices: string[] = []; | |
let start = -1; | |
for (let pos = 0, len = str.length; pos < len; pos++) { | |
if (fn(str.charCodeAt(pos))) { | |
if (start !== -1) { | |
slices.push(str.slice(start, pos)); | |
start = -1; | |
} | |
} else { | |
if (start === -1) { | |
start = pos; | |
} | |
} | |
} | |
if (start !== -1) { | |
slices.push(str.slice(start)); | |
} | |
return slices; | |
}; | |
const str = '"from:me hello world" from:me hello world since:2024-04-13 until:2024-04-14'; | |
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/; | |
// https://github.com/bluesky-social/indigo/blob/421e4da5307f4fcba51f25b5c5982c8b9841f7f6/search/parse_query.go#L15-L21 | |
let quoted = false; | |
const parts = fieldsfunc(str, (rune) => { | |
if (rune === 34) { | |
quoted = !quoted; | |
} | |
return rune === 32 && !quoted; | |
}); | |
for (let i = 0, il = parts.length; i < il; i++) { | |
const part = parts[i]; | |
if (part.charCodeAt(0) === 34) { | |
continue; | |
} | |
const colon_index = part.indexOf(':'); | |
if (colon_index === -1) { | |
continue; | |
} | |
const operator = part.slice(0, colon_index); | |
const value = part.slice(colon_index + 1); | |
if (operator === 'since' || operator === 'until') { | |
const match = DATE_RE.exec(value); | |
if (match === null) { | |
continue; | |
} | |
const s = operator === 'since'; | |
const [, year, month, day] = match; | |
const date = new Date(+year, +month - 1, +day, s ? 0 : 23, s ? 0 : 59, s ? 0 : 59, s ? 0 : 999); | |
if (Number.isNaN(date.getTime())) { | |
continue; | |
} | |
parts[i] = `${operator}:${date.toISOString()}`; | |
} | |
} | |
console.log(parts.join(' ')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment