Last active
August 27, 2023 16:24
-
-
Save sudojunior/1ad009df54ee05ca8765ac7c6a611413 to your computer and use it in GitHub Desktop.
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
// https://stackoverflow.com/a/19277804 | |
function getFurthestFrom(target: number, list: number[]) { | |
const outcome: string[] = []; | |
let record = 0; | |
for (const index in list) { | |
const entry = list[index]; | |
const distance = Math.abs(entry - target); | |
if (distance === record) { | |
outcome.push(index); | |
} else if (distance > record) { | |
outcome.splice(0, outcome.length, index); | |
record = distance; | |
} | |
} | |
return outcome.map((entry) => [entry, list[entry]]); | |
} | |
function getClosestTo(target: number, list: number[]) { | |
const outcome: string[] = []; | |
let record = Infinity; | |
for (const index in list) { | |
const entry = list[index]; | |
const distance = Math.abs(entry - target); | |
if (distance === record) { | |
outcome.push(index); | |
} else if (distance < record) { | |
outcome.splice(0, outcome.length, index); | |
record = distance; | |
} | |
} | |
return outcome.map((entry) => [entry, list[entry]]); | |
} | |
function buildDistancePredicate( | |
callback: (target: number, entry: number) => boolean, | |
initial: number | |
) { | |
return function (target: number, list: number[]) { | |
const outcome: string[] = []; | |
let record = initial; | |
for (const index in list) { | |
const entry = list[index]; | |
const distance = callback(target, entry); | |
if (distance === record) { | |
outcome.push(index); | |
} else if (distance > record) { | |
outcome.splice(0, outcome.length, index); | |
record = distance; | |
} | |
} | |
return outcome.map((entry) => [entry, list[entry]]); | |
} | |
} | |
// Using the predicate in an attempt to reduce the code footprint | |
// Although the use of standardized code would likely be better to trace the stack | |
// const getFurthestFrom2 = buildDistancePredicate((target, entry) => Math.abs((entry - (target / 2)), 0); | |
// const getClosestTo2 = buildDistancePredicate((target, entry) => Math.abs((entry - (target / 2)), Infinity); | |
const getFurthestFromFactor = buildDistancePredicate((target, entry) => Math.abs((entry - (target / 2)) % target), 0); | |
const getClosestToFactor = buildDistancePredicate((target, entry) => Math.abs((entry - (target / 2)) % target), Infinity); | |
// console.log(getFurthestFrom(10, [5, 15])); | |
// console.log(getClosestTo(10, [5, 15])); | |
console.log(getFurthestFromFactor(20, [4, 5, 6, 15])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment