Skip to content

Commit

Permalink
Convert simple class to function+object
Browse files Browse the repository at this point in the history
  • Loading branch information
jridgewell committed Apr 23, 2022
1 parent b1c3826 commit 90a5b6b
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 12 deletions.
14 changes: 10 additions & 4 deletions src/fast-string-array.ts
@@ -1,3 +1,8 @@
export interface FastStringArray {
indexes: { [key: string]: number };
array: readonly string[];
}

/**
* FastStringArray acts like a `Set` (allowing only one occurrence of a string
* `key`), but provides the index of the `key` in the backing array.
Expand All @@ -6,9 +11,11 @@
* the backing array, like how `sourcesContent[i]` is the source content
* associated with `source[i]`, and there are never duplicates.
*/
export class FastStringArray {
indexes = Object.create(null) as { [key: string]: number };
array = [] as ReadonlyArray<string>;
export function FastStringArray(): FastStringArray {
return {
indexes: { __proto__: null } as any,
array: [],
};
}

/**
Expand All @@ -29,4 +36,3 @@ export function put(strarr: FastStringArray, key: string): number {

return index;
}

4 changes: 2 additions & 2 deletions src/source-map-tree.ts
Expand Up @@ -17,8 +17,8 @@ type MappingSource = SourceMapSegmentObject | typeof INVALID_MAPPING | typeof SO
*/
export function traceMappings(tree: SourceMapTree): TraceMap {
const mappings: SourceMapSegment[][] = [];
const names = new FastStringArray();
const sources = new FastStringArray();
const names = FastStringArray();
const sources = FastStringArray();
const sourcesContent: (string | null)[] = [];
const { sources: rootSources, map } = tree;
const rootNames = map.names;
Expand Down
14 changes: 8 additions & 6 deletions test/unit/fast-array-string.ts
@@ -1,14 +1,10 @@
import { FastStringArray, put } from '../../src/fast-string-array';

describe('FastStringArray', () => {
let array: FastStringArray;

beforeEach(() => {
array = new FastStringArray();
});

describe('put()', () => {
test('puts string in if not present', () => {
const array = FastStringArray();

put(array, 'test');
expect(array.array).toEqual(['test']);
put(array, 'test');
Expand All @@ -26,12 +22,16 @@ describe('FastStringArray', () => {
});

test('returns index of string in array', () => {
const array = FastStringArray();

expect(put(array, 'test')).toBe(0);
expect(put(array, 'foo')).toBe(1);
expect(put(array, 'bar')).toBe(2);
});

test('returns original index of string in array', () => {
const array = FastStringArray();

put(array, 'test');
put(array, 'foo');
put(array, 'bar');
Expand All @@ -42,6 +42,8 @@ describe('FastStringArray', () => {
});

test('handles empty string', () => {
const array = FastStringArray();

expect(put(array, '')).toBe(0);
expect(put(array, '')).toBe(0);
expect(array.array).toEqual(['']);
Expand Down

0 comments on commit 90a5b6b

Please sign in to comment.