Skip to content

Instantly share code, notes, and snippets.

@LeeCheneler
Last active April 14, 2020 11:38
Show Gist options
  • Select an option

  • Save LeeCheneler/1d821a837f0e0a685e38f906c70219ba to your computer and use it in GitHub Desktop.

Select an option

Save LeeCheneler/1d821a837f0e0a685e38f906c70219ba to your computer and use it in GitHub Desktop.
expect.toContainInOrder
import chalk from "chalk";
const containsInOrder = (received: string[], expected: string[]) => {
let lastIndex = 0;
const lastOccuranceMap: { [key: string]: number } = {};
for (let e of expected) {
const index = received.indexOf(e);
// Not present at all
if (index === -1) {
return false;
}
// Cater for previous occurences of the expected string
const lastOccuredIndex = lastOccuranceMap[e];
const adjustedIndex =
lastOccuredIndex !== undefined
? received.indexOf(e, lastOccuredIndex + 1)
: index;
// Occurred out of order
if (adjustedIndex < lastIndex) {
return false;
}
// Update
lastOccuranceMap[e] = adjustedIndex;
lastIndex = adjustedIndex;
}
return true;
};
expect.extend({
toContainInOrder: (received: string[], expected: string[]) => {
const recievedStr = chalk.red(`[${received.join("', '")}]`);
const expectedStr = chalk.green(`[${expected.join("', '")}]`);
const pass = containsInOrder(received, expected);
if (pass) {
return {
message: () =>
`expected ${recievedStr} to not contain ${expectedStr} in order`,
pass,
};
} else {
return {
message: () =>
`expected ${recievedStr} to contain ${expectedStr} in order`,
pass,
};
}
},
});
/*
it("is correct", () => {
expect(containsInOrder(["1", "2", "3"], ["1", "2", "3"])).toBe(true);
expect(containsInOrder(["1", "2", "3"], ["1", "3"])).toBe(true);
expect(containsInOrder(["1", "2", "2", "3"], ["2", "3"])).toBe(true);
expect(containsInOrder(["1", "2", "3", "3"], ["2", "3", "3"])).toBe(true);
expect(containsInOrder(["1", "4", "1", "4"], ["1", "4", "1", "4"])).toBe(
true
);
expect(containsInOrder(["1", "3", "2"], ["1", "2", "3"])).toBe(false);
expect(containsInOrder(["1", "3", "3"], ["1", "2", "3"])).toBe(false);
expect(containsInOrder(["1", "3", "3"], ["2", "3"])).toBe(false);
expect(containsInOrder(["1", "3", "3", "2"], ["2", "3"])).toBe(false);
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment