Skip to content

Instantly share code, notes, and snippets.

@taktamur
Created August 3, 2020 00:00
Show Gist options
  • Save taktamur/df926be234bcdb1807afc4d2f62b5fb3 to your computer and use it in GitHub Desktop.
Save taktamur/df926be234bcdb1807afc4d2f62b5fb3 to your computer and use it in GitHub Desktop.
範囲検索の実装テスト
// リソースをRangeに変換
// 指定範囲をRangeに変換
// Range同士のANDを取る
interface ResourceRange {
start: number;
length: number;
}
function convertLengthToResourceRange(
length: number[],
start: number = 0
): ResourceRange[] {
if (length.length === 0) {
return [];
}
const ret: ResourceRange = { start: start, length: length[0] };
return [ret].concat(
convertLengthToResourceRange(length.splice(1), start + length[0])
);
}
it("convertResourceLengthToRange", () => {
const ret = convertLengthToResourceRange([10, 10, 10, 10, 10]);
expect(ret[0]).toEqual({ start: 0, length: 10 });
expect(ret[1]).toEqual({ start: 10, length: 10 });
expect(ret[2]).toEqual({ start: 20, length: 10 });
expect(ret[3]).toEqual({ start: 30, length: 10 });
expect(ret[4]).toEqual({ start: 40, length: 10 });
});
function collition(a: ResourceRange, b: ResourceRange): ResourceRange | null {
const startIndex = Math.max(a.start, b.start);
const endIndex = Math.min(a.start + a.length, b.start + b.length);
return startIndex < endIndex
? { start: startIndex, length: endIndex - startIndex }
: null;
}
it("collition", () => {
expect(
collition({ start: 0, length: 10 }, { start: 0, length: 10 })
).toEqual({ start: 0, length: 10 });
expect(
collition({ start: 0, length: 10 }, { start: 5, length: 10 })
).toEqual({ start: 5, length: 5 });
expect(
collition({ start: 0, length: 10 }, { start: 10, length: 10 })
).toEqual(null);
expect(
collition({ start: 0, length: 10 }, { start: 15, length: 20 })
).toEqual(null);
});
it("hoge", () => {
const selectRange = { start: 15, length: 20 };
const ret = convertLengthToResourceRange([10, 10, 10, 10, 10]);
const a = ret.map((range) => {
return collition(range, selectRange);
});
expect(a[0]).toEqual(null);
expect(a[1]).toEqual({ start: 15, length: 5 });
expect(a[2]).toEqual({ start: 20, length: 10 });
expect(a[3]).toEqual({ start: 30, length: 5 });
expect(a[4]).toEqual(null);
const b: (ResourceRange | null)[] = a.map((range, i) => {
if (range == null) {
return null;
}
return { start: range.start - ret[i].start, length: range.length };
});
expect(b[0]).toEqual(null);
expect(b[1]).toEqual({ start: 5, length: 5 });
expect(b[2]).toEqual({ start: 0, length: 10 });
expect(b[3]).toEqual({ start: 0, length: 5 });
expect(b[4]).toEqual(null);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment