Skip to content

Instantly share code, notes, and snippets.

@shayan-ys
Created March 1, 2020 19:13
Show Gist options
  • Save shayan-ys/a3ffb3ecca9df6e13ec4a6293c455711 to your computer and use it in GitHub Desktop.
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
// 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();
})();
@shayan-ys
Copy link
Author

Run the code at: jsfiddle.net/shayan_ys/5qos4agz
The question was found on HackerRank

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment