Skip to content

Commit

Permalink
Add new Circular#filter(fn) class method
Browse files Browse the repository at this point in the history
  • Loading branch information
klaudiosinani committed Apr 2, 2019
1 parent 67781ff commit 32f6aa2
Showing 1 changed file with 61 additions and 49 deletions.
110 changes: 61 additions & 49 deletions src/circular.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,63 @@ class Circular extends List {
return this;
}

filter(fn) {
const list = new Circular();

this.forEach(x => {
if (fn(x)) {
list.append(x);
}
});

return list;
}

forEach(fn) {
let {_head: node} = this;

if (node) {
do {
fn(node.value);
node = node.next;
} while (node !== this._head);
}

return this;
}

insert({value, index = this.length}) {
this._arrayify(value).forEach(value => {
return (index <= 0) ? this._addHead(value) : this._addNode(value, index);
});
return this;
}

join(separator = ',') {
let result = '';
let {_head: node} = this;

if (node) {
do {
result += node.value;

if (node.next !== this._head) {
result += separator;
}

node = node.next;
} while (node !== this._head);
}

return result;
}

map(fn) {
const list = new Circular();
this.forEach(x => list.append(fn(x)));
return list;
}

prepend(...values) {
values.forEach(value => {
if (this.isEmpty()) {
Expand All @@ -86,13 +143,6 @@ class Circular extends List {
return result;
}

insert({value, index = this.length}) {
this._arrayify(value).forEach(value => {
return (index <= 0) ? this._addHead(value) : this._addNode(value, index);
});
return this;
}

remove(index = this.length - 1) {
if (!this._isValid(index)) {
return undefined;
Expand All @@ -105,17 +155,10 @@ class Circular extends List {
return this._removeNode(index);
}

forEach(fn) {
let {_head: node} = this;

if (node) {
do {
fn(node.value);
node = node.next;
} while (node !== this._head);
}

return this;
reverse() {
const list = new Circular();
this.forEach(x => list.prepend(x));
return list;
}

toArray() {
Expand All @@ -130,37 +173,6 @@ class Circular extends List {
this.forEach(x => list.append(x));
return list;
}

map(fn) {
const list = new Circular();
this.forEach(x => list.append(fn(x)));
return list;
}

join(separator = ',') {
let result = '';
let {_head: node} = this;

if (node) {
do {
result += node.value;

if (node.next !== this._head) {
result += separator;
}

node = node.next;
} while (node !== this._head);
}

return result;
}

reverse() {
const list = new Circular();
this.forEach(x => list.prepend(x));
return list;
}
}

module.exports = Circular;

0 comments on commit 32f6aa2

Please sign in to comment.