Skip to content

Instantly share code, notes, and snippets.

View dragonza's full-sized avatar

Alex Vuong dragonza

View GitHub Profile
@dragonza
dragonza / reverseInt.js
Last active February 4, 2018 17:06
Reverse an integer
function reverseInt(n) {
const reversed = n.toString().split('').reverse().join(''); // turn a number into a string, then turn it into an array to reverse.
return Math.sign(n) * parseInt(reversed); // Math.sign will return -1 as for negative number, 1 as for position number, 0 as for zero.
}
@dragonza
dragonza / maxChar.js
Last active February 12, 2018 17:32
Find the most commonly used character in string
function maxChar(str) {
const charMap = {};
let max = 0;
let maxChar = '';
// create character map
for (let char of str) {
if (charMap[char]) {
// increment the character's value if the character existed in the map
charMap[char]++;
@dragonza
dragonza / characterMap.js
Created February 12, 2018 17:34
Create character map
const obj = {};
for (let char of str) {
obj[char] = obj[char] + 1 || 1;
}
@dragonza
dragonza / characterMap.js
Last active February 12, 2018 17:38
Create character map
const obj = {};
str.split('').forEach(char => obj[char] + 1 || 1); // remember to turn the given string into array first as forEach is Array prototype
Object.keys(obj).forEach(char => {
if (obj[char] > max) {
maxChar = char;
max = obj[char];
}
});
@dragonza
dragonza / maxChar.js
Created February 12, 2018 17:53
Find commonly used character
return Object.keys(obj).reduce((prev, next) => obj[a] >= obj[b] ? a : b);
@dragonza
dragonza / maxChar.js
Created February 12, 2018 18:01
Find commonly used character
function maxChar(str) {
const obj = {};
str.split('').forEach(char => obj[char] + 1 || 1);
return Object.keys(obj).reduce((prev, next) => obj[a] >= obj[b] ? a : b);
}
@dragonza
dragonza / chunk.js
Last active July 10, 2020 17:15
Chunk array
function chunk(array, size) {
const chunked_arr = [];
for (let i = 0; i < array.length; i++) {
const last = chunked_arr[chunked_arr.length - 1];
if (!last || last.length === size) {
chunked_arr.push([array[i]]);
} else {
last.push(array[i]);
}
}
@dragonza
dragonza / chunk.js
Last active February 19, 2018 10:49
Chunk array
function chunk(array, size) {
const chunked_arr = [];
let copied = [...array]; // ES6 destructuring
const numOfChild = Math.ceil(copied.length / size); // Round up to the nearest integer
for (let i = 0; i < numOfChild; i++) {
chunked_arr.push(copied.splice(0, size));
}
return chunked_arr;
}
@dragonza
dragonza / chunk.js
Created February 19, 2018 11:05
Chunk array
function chunk(array, size) {
const chunked_arr = [];
let index = 0;
while (index < array.length) {
chunked_arr.push(array.slice(index, size + index));
index += size;
}
return chunked_arr;
}