1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| class App {
constructor(...args) {
if ( args.length === 2 )
[this.name, this.version] = args;
else
[this.name, ...this.version] = this._parse(args[0]);
}
_parse(appStr) {
return appStr.split(/[,.]/);
}
toString() {
return `${this.name},${this.version.join('.')}`;
}
}
class VersionSet extends Set {
static compare(a, b) {
if ( typeof a === 'undefined' )
return -1;
return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
}
lastVersion() {
let lastVersion;
for (const version of this) {
if ( VersionSet.compare(lastVersion, version) < 0 )
lastVersion = version;
}
return lastVersion;
}
}
class AppCollection extends Map {
set(app) {
if ( !this.has(app.name) )
super.set(app.name, new VersionSet());
super.get(app.name).add(app.version);
}
lastVersions() {
const lastVersions = [];
for (let [name, versions] of this) {
lastVersions.push(new App(name, versions.lastVersion()));
}
return lastVersions;
}
}
const appList = [ 'A,6.3.0', 'B,3.2.3', 'F,5.8.0', 'G,12.2.0', 'C,4.3.1',
'M,5.1.0', 'R,5.4.1', 'F,5.6.0', 'R,5.2.1', 'A,6.2.0', 'B,3.2.0',
'M,5.0.0', 'C,4.3.0', 'G,8.1.3'];
let coll = new AppCollection();
for (const app of appList) {
coll.set(new App(app));
}
console.log(coll.lastVersions().map((app) => `${app}`)); |
Partager