Skip to content

Instantly share code, notes, and snippets.

@martinlaws
Created January 9, 2020 21:02
Show Gist options
  • Save martinlaws/7fa4b8316e7ebc2cf6dc57e5475d3aac to your computer and use it in GitHub Desktop.
Save martinlaws/7fa4b8316e7ebc2cf6dc57e5475d3aac to your computer and use it in GitHub Desktop.
// Option 1: Math.min()
const findSmallestIntUsingMathMin = args => {
return Math.min(...args);
};
console.log(findSmallestIntUsingMathMin([1, 2, 3, 4, 0, 5]));
// Option 2: Array.reduce()
const reducer = (minValue, currentValue) =>
minValue < currentValue ? minValue : currentValue;
const findSmallestIntUsingReduce = args => {
return args.reduce(reducer);
};
console.log(findSmallestIntUsingReduce([1, 2, -3, 4, 5]));
const findSmallestIntUsingMathMin = args => {
return Math.min(...args)
};
const findSmallestInt = args => {
return args.sort((a,b) => a - b)[0]
};
console.log(findSmallestInt([1, 2, 3, 4, -10, 5]));
// Martin's preferred solution:
function romanize(num) {
const romanMatrix = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
};
let roman = "";
for (let key of Object.keys(romanMatrix)) {
const quotient = Math.floor(num / romanMatrix[key]);
num -= quotient * romanMatrix[key];
roman += key.repeat(quotient);
}
return roman;
}
console.log(romanize(1234));
// Top StackOverflow Solution:
function romanize (num) {
if (isNaN(num))
return NaN;
var digits = String(+num).split(""),
key = ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",
"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",
"","I","II","III","IV","V","VI","VII","VIII","IX"],
roman = "",
i = 3;
while (i--)
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
return Array(+digits.join("") + 1).join("M") + roman;
}
// Second StackOverFlow Solution:
function romanize(num) {
var lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1},roman = '',i;
for ( i in lookup ) {
while ( num >= lookup[i] ) {
roman += i;
num -= lookup[i];
}
}
return roman;
}
function romanize(num) {
const lookup = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
};
}
console.log(romanize(123));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment