Created
March 1, 2020 19:13
-
-
Save shayan-ys/a3ffb3ecca9df6e13ec4a6293c455711 to your computer and use it in GitHub Desktop.
Count pairs of socks in a merchant array - JS functional programming using variable closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// run the code at: https://jsfiddle.net/shayan_ys/5qos4agz/ | |
// question found on HackerRank: https://www.hackerrank.com/challenges/sock-merchant?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup | |
function isPair(x, pairs) { | |
return pairs.hasOwnProperty(x); | |
} | |
var processMerchant = (function () { | |
var pairs = {}; | |
var pairsCount = 0; | |
function processValue(value) { | |
if (isPair(value, pairs)) { | |
delete pairs[value]; | |
pairsCount++; | |
} else { | |
pairs[value] = true; | |
} | |
} | |
function countPairs(n, ar) { | |
ar.map((i) => { | |
processValue(i); | |
return i; | |
}); | |
return pairsCount; | |
} | |
return countPairs; | |
})(); | |
function sockMerchant(n, ar) { | |
return processMerchant(n, ar); | |
} | |
var init = (function() { | |
var n = 9; | |
var ar = [10, 20, 20, 10, 10, 30, 50, 10, 20]; | |
let pairs = sockMerchant(n, ar); | |
console.log(pairs); | |
document.getElementById("result").innerText = pairs.toString(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run the code at: jsfiddle.net/shayan_ys/5qos4agz
The question was found on HackerRank