Skip to content

Instantly share code, notes, and snippets.

@sudojunior
Last active August 11, 2022 23:42
Show Gist options
  • Save sudojunior/ab06cc7583726f1c521b9019c79904ad to your computer and use it in GitHub Desktop.
Save sudojunior/ab06cc7583726f1c521b9019c79904ad to your computer and use it in GitHub Desktop.
'expand' and 'shrink' year ranges, made in about an hour after an initial version in js only with the expand function
export class YearRange {
static testPattern = /[\d -,]+/g;
static splitPattern = / *[-,] */g;
private static getContext(input: string): YearRangeContext {
console.assert(this.testPattern.test(input), 'Invalid pattern match');
const fragments = input.split(this.splitPattern);
const symbols = input.match(this.splitPattern) ?? [];
console.assert(fragments[0].length === 4, 'Invalid initial year range');
return { fragments, symbols };
}
static expand(input: string): string {
const { fragments, symbols } = this.getContext(input);
if (symbols.length === 0) return fragments[0];
const output: string[] = [];
let previousYear = '';
for (const index in fragments) {
const fragment = fragments[index];
let result: string = fragment;
if (index !== '0') {
result = previousYear.substring(0, previousYear.length - fragment.length) + fragment;
}
output.push(result);
previousYear = result;
}
return String.raw({ raw: output }, ...symbols);
}
static shrink(input: string): string {
const { fragments, symbols } = this.getContext(input);
if (symbols.length === 0) return fragments[0];
const output: string[] = [];
let previousYear = '';
for (const index in fragments) {
const fragment = fragments[index];
let result: string = fragment;
if (index !== '0') {
const index = result
.slice()
.split('')
.findIndex((char, index) => char === previousYear[index]);
result = result.slice(result.length - index - 1);
}
output.push(result);
previousYear = fragment;
}
return String.raw({ raw: output }, ...symbols);
}
}
interface Context {
fragments: string[];
symbols: string[];
}
export type YearRangeContext = Context;
console.log(YearRange.shrink('2002 - 2003,2005'));
@sudojunior
Copy link
Author

console.log(YearRange.expand('2002 - 3, 5') // 2002 - 2003, 2005
console.log(YearRange.shrink('2002-2003,2005') // 2002-3,5

@sudojunior
Copy link
Author

Known issues with providing year strings in the incorrect order (shrink: 2012 - 2003), it's not something I'm willing to fix given the time in which it was smashed together. While expand doesn't validate any of this, it continues to work as intended regardless of the flaws that its sibling has.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment