I need/want to extend created array instance, to add extra methods that i see as useful.
class.labels.js
const {
find,
filter,
value,
key
} = require("./labels.js");
module.exports = class Labels extends Array {
constructor(...args) {
super(...args);
}
find(...args) {
return find(this, ...args);
}
filter(...args) {
return filter(this, ...args);
}
value(...args) {
return value(this, ...args);
}
key(...args) {
return key(this, ...args);
}
};
labels.js
function match(label, filter) {
let [fk, fv] = filter.split("=");
let [lk, lv] = label.split("=");
if (fv === "*") {
return fk === lk;
}
if (fk === "*") {
return fv === lv;
}
return label === filter;
}
function find(arr, filter) {
return Array.prototype.find.call(arr, (label) => {
return match(label, filter);
});
}
function filter(arr, filter) {
return Array.prototype.find.call(arr, (label) => {
return match(label, filter);
});
}
function value(arr, key) {
return find(arr, `${key}=*`)?.split("=")[1];
}
function key(arr, val) {
return find(arr, `*=${val}`)?.split("=")[0];
}
module.exports = {
match,
find,
filter,
value,
key
};
example.js
const Labels = require("./class.labels.js");
const labels = new Labels();
labels.push("key=value");
labels.push("foo=bar");
labels.push("bar=baz");
labels.push("key1=value")
console.log(labels);
console.log(labels.find("foo=*"));
console.log(labels.map((s) => {
return String.prototype.toUpperCase.call(s);
}));
console.log(labels.key("value"));
console.log(labels.value("key1"));
Is this praxis considered ok?