Reputation: 629
I did a findMaxChar count algorithm practice, manage to get it to worked but my call method can be improved.
const myStr = 'Lorem Ipsummm'
function findRepeatable(myStr){
let charMap = {}
for(let char of myStr){
if(charMap[char]) {
charMap[char]++
}else{
charMap[char] = 1
}
}
return charMap
}
function findMostRepeated(obj){
let maxChar = '',
max = 0
for(let char in obj){
if(obj[char] > max){
max = obj[char]
maxChar = char
}
}
return `${maxChar}: ${max}`
}
console.log(findMostRepeated(findRepeatable(myStr)))
I'm passing function as argument, how can I make it to chain like this
findMostRepeated()
.findRepeatable()
https://jsbin.com/katixefoxe/edit?html,js,console
Upvotes: 0
Views: 1015
Reputation: 30009
Many functional libraries come with a pipe function that can be used for "chaining".
pipe(findRepeatable, findMostRepeated)(myStr)
It's easy to implement yourself.
function pipe(...funcs) {
return function(value) {
for (func of funcs) {
value = value(func)
}
return value;
}
}
Upvotes: 1
Reputation: 65
try:
const myStr = 'Lorem Ipsummm'
var myObj ={
charMap:{},
findRepeatable:function (myStr){
for(let char of myStr){
if(this.charMap[char]) {
this.charMap[char]++
}else{
this.charMap[char] = 1
}
}
return this;
},
findMostRepeated: function (obj){
let maxChar = '',
max = 0
for(let char in this.charMap){
if(this.charMap[char] > max){
max = this.charMap[char]
maxChar = char
}
}
return `${maxChar}: ${max}`;
}
}
console.log(myObj.findRepeatable(myStr).findMostRepeated())
Upvotes: 0
Reputation: 138537
class CharMap extends Map {
constructor(str){
super();
for(var char of str)
this.add(char);
}
add(char){
this.set(char, (this.get(char) || 0) + 1);
}
max(){
return this.sortDesc()[0];
}
sortDesc(){
return [...this].sort(([char, a], [char2, b]) => b - a);
}
}
So you can do:
const map = new CharMap("abbccddeee");
console.log(map.max());
To get the char and its count:
const [char, count] = map.max();
Upvotes: 0