Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save median-man/548b2e00da349268601f540d9e9a45ad to your computer and use it in GitHub Desktop.
Save median-man/548b2e00da349268601f540d9e9a45ad to your computer and use it in GitHub Desktop.
//see if sequence of nums is in increasing order, but seq is allowed to decrease once.
// The Goldilocks solution
function checkSequence(arr) {
const maxOutOfSequencePermitted = 1
let countOfOutOfSequence = 0
for (let i = 1; i < arr.length; i += 1) {
if (arr[i] < arr[i - 1]) {
countOfOutOfSequence += 1
}
if (countOfOutOfSequence > maxOutOfSequencePermitted) {
return false
}
}
return true
}
function logSuccess(fn) {
return arr => console.log(fn(arr) ? 'success' : 'failure')
}
logSuccess(checkSequence)([0, 1, 2, 3, 5, 4, 5, 7])
//see if sequence of nums is in increasing order, but seq is allowed to decrease once.
//some shared stuff first:
// Easier to read. (If not overly verbose)
function checkSequence(arr) {
let countOfOutOfSequence = 0
for (let i = 1; i < arr.length; i += 1) {
if (isOutOfSequence(i)) {
countOfOutOfSequence += 1
}
if (hasTooManyOutOfSequence()) {
return false
}
}
return true
function isOutOfSequence(i) {
return arr[i] < arr[i - 1]
}
function hasTooManyOutOfSequence() {
const maxAllowableOutOfSequence = 1
return countOfOutOfSequence > maxAllowableOutOfSequence
}
}
function logSuccess(fn) {
return arr => console.log(fn(arr) ? 'success' : 'failure')
}
logSuccess(checkSequence)([0, 1, 2, 3, 5, 4, 5, 7])
//see if sequence of nums is in increasing order, but seq is allowed to decrease once.
//some shared stuff first:
// Abusing the ternary
function checkSequence(arr) {
return (
arr.reduce(
(decreaseCount, num, index) =>
index === 0
? 0
: num < arr[index - 1]
? decreaseCount + 1
: decreaseCount,
0
) <= 1
)
}
function logSuccess(fn) {
return arr => console.log(fn(arr) ? 'success' : 'failure')
}
logSuccess(checkSequence)([0, 1, 2, 3, 5, 4, 5, 7])
/*
The following code tests checkSequence:
*/
const tests = [
{
name: '2 elements',
testFn: () => {
const arr = [0, 1]
assertEquals(checkSequence(arr), true)
}
},
{
name: 'decreases twice',
testFn: () => {
const arr = [0, 1, 0, 1, 0]
assertEquals(checkSequence(arr), false)
}
},
{
name: 'decreases once',
testFn: () => {
const arr = [0, 1, 2, 3, 5, 4, 5, 7]
assertEquals(checkSequence(arr), true)
}
}
]
function assertEquals(actual, expected) {
if (actual !== expected) {
throw new Error(`Expected ${actual} to equal ${expected}.`)
}
}
function runTest(testName, testFn) {
try {
testFn()
console.log(`Passed test "${testName}".\n`)
} catch (err) {
console.log(`Failed test "${testName}":\n\n`)
console.log(err)
console.log('\n\n')
}
}
tests.forEach(({ name, testFn }) => runTest(name, testFn))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment