Examples of function currying using javascript

 Examples of function currying using javascript


export function transform(str) {
// // Input: a3b3c6d5
// Output: aaaaabbbccccccddddd

const strArray = str.split('');
const map = {};
let lastChar = strArray[0];
let tmp = ''
strArray.forEach(char => {
if(isNaN(char)) {
map[char] = 0;

if(lastChar) {
map[lastChar] = Number(tmp);
lastChar = char;
tmp = '';
}
} else {
tmp += char;
}
})

// map last characters repition here
if(tmp) {
map[lastChar] = Number(tmp);
tmp = '';
}

let output = '';
Object.keys(map).map(key => {
let charRepeatation = map[key];
for(let i=0; i<charRepeatation; i++) {
output += key;
}
})

return output;

}

export function transformWithTimer(input) {
var promise = new Promise(res => {
setTimeout(() => {
res(transform(input));
}, 2000);
});
return promise;
}

// transformWithTimer('a10b3c6d7').then(res => {
// console.log('hello out: ', res);
// })

// curry
function mul(p) {
console.log('mul: ', p);
var n = (n || 1) * p;
return function () {
if(arguments.length) {
console.log(arguments[0]);
return mul(n * arguments[0])
} else {
console.log('else: ', n);
return n;
}
}
}

// console.log(mul(3)(5)(4)());

function pul(p) {
return function () {
console.log('mul: ', p);
if(arguments.length) {
return pul(p * arguments[0])
} else {
return p;
}
}
}

// console.log(pul(3)(5)(4)());

// recursion

function fibo(n) {
if(n > 1) {
// console.log('if: ', n * fibo(n-1));
return n * fibo(n-1);
} else {
// console.log('else: ', n);
return n;
}
}
console.log(fibo(5));

Comments

Popular posts from this blog

Abhijit Padhy

Find the longest substring in a given string.

Find the robot matching the given query having [top, right, bottom, left] index of the nearest walls in a 2D array.