Skip to content

Commit

Permalink
feat: Add debug operator (#34)
Browse files Browse the repository at this point in the history
This operator can be inserted in a callbag chain (e.g. in a call to
`pipe`) to log all the events that flow through
  • Loading branch information
jvanbruegge authored May 2, 2021
1 parent b47a331 commit 54da601
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Currently, the following set of operators is implemented, others might follow. N

- [`map`](./src/map.ts)
- [`scan`](./src/map.ts)
- [`debug`](./src/map.ts)
- [`take`](./src/take.ts)
- [`first`](./src/take.ts)
- [`filter`](./src/filter.ts)
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export { makeSubject, makeAsyncSubject } from './subject';
export { create, never, empty, throwError } from './identities';

// Operators
export { map, scan } from './map';
export { map, scan, debug } from './map';
export { take, first } from './take';
export { filter } from './filter';
export { startWith } from './startWith';
Expand All @@ -32,5 +32,5 @@ export {
ALL,
START,
DATA,
END
END,
} from './types';
8 changes: 8 additions & 0 deletions src/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,11 @@ export function scan<A, B>(
});
};
}

export function debug<A>(msg: string | ((a: A) => void)): Operator<A, A> {
const f = typeof msg === 'function' ? msg : (x: A) => console.log(msg, x);
return map(x => {
f(x);
return x;
});
}
55 changes: 55 additions & 0 deletions test/debug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import * as assert from 'assert';
import { pipe, debug, subscribe, fromArray } from '../src/index';

describe('debug', () => {
const log = console.log;

it('should log to console when given a string', () => {
const logs: [string, number][] = [];
console.log = (x: string, y: number) => {
logs.push([x, y]);
};
let called = false;

pipe(
fromArray([1, 2, 3, 4]),
debug('message'),
subscribe(
() => {},
() => {
const expected = [
['message', 1],
['message', 2],
['message', 3],
['message', 4],
];
assert.deepStrictEqual(logs, expected);
called = true;
}
)
);

assert.strictEqual(called, true);
console.log = log;
});

it('should call given function with data', () => {
const logs: number[] = [];
const expected = [1, 2, 3, 4];
let called = false;

pipe(
fromArray(expected),
debug(x => logs.push(x)),
subscribe(
() => {},
() => {
assert.deepStrictEqual(logs, expected);
called = true;
}
)
);

assert.strictEqual(called, true);
});
});

0 comments on commit 54da601

Please sign in to comment.