π Replit
β‘οΈ restParameter
function sum4(...args){
let total = 0;
const reducer = (prev, cur) => {
}
args.reduce(reducer)
return total
}
console.log(sum4(5,7,2));
function sum4(...args){
let total = 0;
console.log(args)
const reducer = (prev, cur) => {
console.log(prev)
return prev + cur
}
total = args.reduce(reducer)
return total
}
console.log(sum4(5,7,2));
β‘οΈ new Set
function common(arr1, arr2){
arr1 = new Set(arr1)
arr2 = new Set(arr2)
let result = new Set([...arr1].filter(x => arr2.has(x)))
console.log([...result])
return result.size
}
let a = ['a', 'b', 'c', 'c', 'b'];
let b = ['b', 'b', 'b', 'c', 'e', 'e', 'f'];
console.log(common(a, b));
β‘οΈ new Map
function classification(str){
let map = new Map([['A',1],['B',2],['C',3]]);
for (let i = 0; i<str.length; i++){
switch(str[i]){
case 'A':
map.set('A', map.get('A') + 1)
break
case 'B':
map.set('B', map.get('B') + 1)
break
case 'C':
map.set('C', map.get('C') + 1)
break
}
}
return map;
}
var str = "ABCCCAA"
console.log(classification(str));
π Vote
function vote(str){
str.split(" ")
let count = {}
for (let a of str){
if (a in count){
count[a] += 1
} else {
count[a] = 1
}
}
let value = Object.values(count)
let max = value[0]
let maxIndex = 0
for(let i = 0; i < value.length; i++){
if (value[i] > max){
max = value[i]
maxIndex = i
}
}
return Object.keys(count)[maxIndex]
}
vote("BACBACCACCBDEDE")
function vote(str){
const strList = [... new Set(str.split('').sort())]
const arr = Array.from(Array(strList.length), (e, i) => [strList[i],0])
let mapVote = new Map(arr)
str.split('').forEach((e) => {
if(mapVote.has(e)){
mapVote.set(e, mapVote.get(e) + 1)
}
})
let answer = [...mapVote].reduce((a,b) => a[1] < b[1] ? b : a)[0]
return answer
}
vote("BACBACCACCBDEDE")
function vote(str){
var sH = new Map()
for(let s of str){
if (sH.has(s)){
sH.set(s, sH.get(s) + 1)
} else {sH.set(s,1)
}
}
let max = 0;
let answer
for (let [k,v] of sH){
if (v>max){
max = v
answer = k
}
}
return answer
}
vote("BACBACCACCBDEDE")