Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(utils): add warn function #3147

Merged
merged 2 commits into from
Sep 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion src/lib/__tests__/utils-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,7 @@ describe('utils.deprecate', () => {
const actual = 6;

expect(actual).toBe(expectation);
expect(warn).toHaveBeenCalled();
expect(warn).toHaveBeenCalledWith('[InstantSearch.js]: message');

warn.mockReset();
warn.mockRestore();
Expand All @@ -899,6 +899,38 @@ describe('utils.deprecate', () => {
});
});

describe('utils.warn', () => {
it('expect to print a warn message', () => {
const message = 'message';
const warn = jest.spyOn(global.console, 'warn');

utils.warn(message);

expect(warn).toHaveBeenCalledWith('[InstantSearch.js]: message');

warn.mockReset();
warn.mockRestore();
utils.warn.cache = {};
});

it('expect to print the same message only once', () => {
const message = 'message';
const warn = jest.spyOn(global.console, 'warn');

utils.warn(message);

expect(warn).toHaveBeenCalledTimes(1);

utils.warn(message);

expect(warn).toHaveBeenCalledTimes(1);

warn.mockReset();
warn.mockRestore();
utils.warn.cache = {};
});
});

describe('utils.parseAroundLatLngFromString', () => {
it('expect to return a LatLng object from string', () => {
const samples = [
Expand Down
20 changes: 18 additions & 2 deletions src/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export {
checkRendering,
isReactElement,
deprecate,
warn,
parseAroundLatLngFromString,
};

Expand Down Expand Up @@ -401,21 +402,36 @@ function isReactElement(object) {
);
}

function logger(message) {
// eslint-disable-next-line no-console
console.warn(`[InstantSearch.js]: ${message.trim()}`);
}

function deprecate(fn, message) {
let hasAlreadyPrint = false;

return function(...args) {
if (!hasAlreadyPrint) {
hasAlreadyPrint = true;

// eslint-disable-next-line no-console
console.warn(`[InstantSearch.js]: ${message}`);
logger(message);
}

return fn(...args);
};
}

warn.cache = {};
function warn(message) {
const hasAlreadyPrint = warn.cache[message];

if (!hasAlreadyPrint) {
warn.cache[message] = true;

logger(message);
}
}

const latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/;
function parseAroundLatLngFromString(value) {
const pattern = value.match(latLngRegExp);
Expand Down