Skip to content

Instantly share code, notes, and snippets.

@klauszhang
Created November 13, 2017 10:17
Show Gist options
  • Save klauszhang/906eae2f8af2eb262000b54d9d14067e to your computer and use it in GitHub Desktop.
Save klauszhang/906eae2f8af2eb262000b54d9d14067e to your computer and use it in GitHub Desktop.
function getNumber(digit = 4) {
return () =>
Math.floor(
Math.random() * Math.pow(10, digit)
);
}
function getNumInRange(digit = 4) {
return function(numberGenerator) {
return function recursiveQuery() {
const newPin = numberGenerator();
return newPin <= Math.pow(10, digit - 1)
? recursiveQuery()
: newPin;
};
};
}
function checkConsecutive(nPlus1, n) {
return nPlus1 - n !== 1;
}
function checkValidity(arr) {
let isValid = true;
let next = 0;
return function checkResursive(idx = 0) {
next = idx + 1;
isValid =
isValid &&
checkConsecutive(arr[idx + 1], arr[idx]);
return next === arr.length - 1
? isValid
: checkResursive(next);
};
}
function getPin(digit) {
return pinGenerator => {
return function ensureInShape() {
const pin = pinGenerator();
const stringArr = pin.toString().split('');
const noDuplicate =
new Set(stringArr).size === digit;
const noConsecutive = checkValidity(
stringArr.map(item => parseInt(item))
)();
return noDuplicate && noConsecutive
? pin
: ensureInShape();
};
};
}
function getSolution(howMany) {
const result = new Set();
return pinGenerator => {
return function getEach() {
result.add(pinGenerator());
if (result.size === howMany) {
return result;
} else {
return getEach();
}
};
};
}
const generator = digits =>
getPin(digits)(
getNumInRange(digits)(getNumber(digits))
);
module.exports = {
getSolution,
generator
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment