所以我只是学习如何使用JS进行编码,所以我只想警告您,我的代码可能对您来说很糟糕。
我想要一个“班级”,该班级可以计算数字的计数频率。
示例:
counter = new Counter();
counter.count(1);
counter.count(1);
counter.count(3);
调用getCounts会得到结果:
counter.getCounts();
> 1: 2, 3: 1
我的代码有效,但是我有两个问题。
我的代码:
class Counter {
constructor(arr = []) {
this.arr = arr;
}
count(number) {
var posNumber = [];
var evenNumCheck = false;
var exactPos;
//Check if have the number already in the array
for (var i = 0; i < this.arr.length; i++) {
if (this.arr[i] === number) {
posNumber.push(i);
}
}
//posNumber we have the position of all the numbers that match our argument number
// we check which of them has an even position, only this can be the number we want
// since we save [number,count; number,count]
for (var i = 0; i < posNumber.length; i++) {
if (i % 2 === 0) {
evenNumCheck = true;
exactPos = i;
}
}
if (evenNumCheck) {
this.arr[exactPos + 1]++;
} else {
this.arr.push(number);
this.arr.push(1);
}
}
getCounts() {
var string = '';
for (var i = 0; i < this.arr.length; i += 2) {
if (i + 2 >= this.arr.length) {
string += this.arr[i] + ': ' + this.arr[i + 1];
} else {
string += this.arr[i] + ': ' + this.arr[i + 1] + ', ';
}
}
console.log(string);
}
}
您认为此解决方案尚可,还是有更好的解决方案,也可能会按顺序输出数字?
答案 0 :(得分:1)
经典方法是使用@Orkhan Alikhanov所说的对象
class Counter {
constructor () {
this.dic = {}
}
count (number) {
if (number in this.dic) {
this.dic[number]++
} else {
this.dic[number] = 1
}
}
getCounts () {
// instead of doing the trailing comma stuff
// make an array of string and join the array
const out = Object.entries(this.dic).map(entry => entry.join(':')).join(',')
console.log(out)
}
}
const counter = new Counter()
counter.count(1)
counter.count(1)
counter.count(2)
counter.getCounts()
您可能更喜欢使用Map,因为从语义上讲,您只想将数字映射到计数。
class Counter {
constructor () {
this.dic = new Map()
}
count (number) {
const count = this.dic.get(number)
this.dic.set(number, count ? count + 1 : 1)
}
getCounts () {
const out = [...this.dic.entries()].map(entry => entry.join(':')).join(',')
console.log(out)
}
}
const counter = new Counter()
counter.count(1)
counter.count(1)
counter.count(2)
counter.getCounts()
最后,如果要打印的数字不是按插入的顺序而是按“ int”的顺序打印,则必须sort个条目:
class Counter {
constructor () {
this.dic = new Map()
}
count (number) {
const count = this.dic.get(number)
this.dic.set(number, count ? count + 1: 1)
}
getCounts () {
const out = [...this.dic.entries()]
.sort((a, b) => a[0] - b[0]) // sort by first key (which is the number)
.map(entry => entry.join(':'))
.join(',')
console.log(out)
}
}
const counter = new Counter()
counter.count(2) // insert 2 before
counter.count(1)
counter.count(1)
counter.getCounts()