Skip to content

Commit

Permalink
feat: add filter() function
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Sep 24, 2018
1 parent 59220b9 commit 1f641f4
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
34 changes: 34 additions & 0 deletions index.js
Expand Up @@ -320,6 +320,40 @@ Kareem.prototype.wrap = function(name, fn, context, args, options) {
});
};

Kareem.prototype.filter = function(fn) {
const clone = this.clone();

const pres = Array.from(clone._pres.keys());
for (const name of pres) {
const hooks = this._pres.get(name).
map(h => Object.assign({}, h, { name: name })).
filter(fn);

if (hooks.length === 0) {
clone._pres.delete(name);
continue;
}

clone._pres.set(name, hooks);
}

const posts = Array.from(clone._posts.keys());
for (const name of posts) {
const hooks = this._posts.get(name).
map(h => Object.assign({}, h, { name: name })).
filter(fn);

if (hooks.length === 0) {
clone._posts.delete(name);
continue;
}

clone._posts.set(name, hooks);
}

return clone;
};

Kareem.prototype.hasHooks = function(name) {
return this._pres.has(name) || this._posts.has(name);
};
Expand Down
38 changes: 38 additions & 0 deletions test/misc.test.js
Expand Up @@ -31,3 +31,41 @@ describe('merge', function() {
assert.equal(k3._pres.get('cook').numAsync, 1);
});
});

describe('filter', function() {
it('returns clone with only hooks that match `fn()`', function() {
const k1 = new Kareem();

k1.pre('update', { document: true }, f1);
k1.pre('update', { query: true }, f2);
k1.pre('remove', { document: true }, f3);

k1.post('update', { document: true }, f1);
k1.post('update', { query: true }, f2);
k1.post('remove', { document: true }, f3);

const k2 = k1.filter(hook => hook.document);
assert.equal(k2._pres.get('update').length, 1);
assert.equal(k2._pres.get('update')[0].fn, f1);
assert.equal(k2._pres.get('remove').length, 1);
assert.equal(k2._pres.get('remove')[0].fn, f3);

assert.equal(k2._posts.get('update').length, 1);
assert.equal(k2._posts.get('update')[0].fn, f1);
assert.equal(k2._posts.get('remove').length, 1);
assert.equal(k2._posts.get('remove')[0].fn, f3);

const k3 = k1.filter(hook => hook.query);
assert.equal(k3._pres.get('update').length, 1);
assert.equal(k3._pres.get('update')[0].fn, f2);
assert.ok(!k3._pres.has('remove'));

assert.equal(k3._posts.get('update').length, 1);
assert.equal(k3._posts.get('update')[0].fn, f2);
assert.ok(!k3._posts.has('remove'));

function f1() {}
function f2() {}
function f3() {}
});
});

0 comments on commit 1f641f4

Please sign in to comment.