Skip to content

Commit

Permalink
Merge pull request #10 from fossapps/fix-padstart
Browse files Browse the repository at this point in the history
fix(padStart): fix padStart call for older browser
  • Loading branch information
cyberhck authored Dec 12, 2019
2 parents c9a9271 + 18fdc97 commit 0a5f7cb
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/adapters/TinyNumberCompressor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import {ValueType} from "../Searilie";
import {TinyNumberCompressor} from "./TinyNumberCompressor";

describe("TinyNumberCompressor", () => {
it("PadStart should work ", () => {
expect(TinyNumberCompressor.leftPad("0", 3, "a")).toBe("aa0");
});

it("should be defined", () => {
expect(TinyNumberCompressor).toBeDefined();
});
Expand Down
17 changes: 16 additions & 1 deletion src/adapters/TinyNumberCompressor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ export class TinyNumberCompressor implements IAdapter {
return (36 ** numOfChars) - 1;
}

public static leftPad(text: string, targetLength: number, padString: string = ""): string {
// tslint:disable-next-line:no-bitwise
targetLength = targetLength >> 0; // truncate if number, or convert non-number to 0;
if (this.length >= targetLength) {
return String(text);
} else {
targetLength = targetLength - text.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); // append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + String(text);
}
}

public deserialize(text: string, schema: ISchema): IObject[] {
const charLengthForSchema = this.getCharLengthForSchema(schema);
if (text.length % charLengthForSchema !== 0) {
Expand Down Expand Up @@ -44,7 +58,8 @@ export class TinyNumberCompressor implements IAdapter {
private encodeObject(object: IObject): string {
return Object.keys(object).sort().map((x) => {
const length = this.keyLengthFactory(x);
return (object[x] as number).toString(36).padStart(length, "0");
const str = (object[x] as number).toString(36);
return TinyNumberCompressor.leftPad(str, length, "0");
}).join("");
}

Expand Down

0 comments on commit 0a5f7cb

Please sign in to comment.