Last active
May 5, 2019 15:35
-
-
Save chetbis/21b12efa6011755c1c88cd62fdaf8f50 to your computer and use it in GitHub Desktop.
javascript utilities
This file contains hidden or 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
//////////////////////////////////////////////////////////////////////////// | |
const obj = { | |
a: 10, | |
b: { | |
c: 20, | |
d: 30, | |
e: { | |
f: 40 | |
} | |
} | |
}; | |
function flattenObject(object, parentKeys = [], parentKeysSeperator = '#') { | |
return Object.keys(object) | |
.reduce((acc, key) => { | |
return { | |
...acc, | |
...( | |
typeof (object) === 'object' ? | |
flattenObject(object[key], [...parentKeys, key]) | |
: | |
{ [`${parentKeys.join(parentKeysSeperator)}${parentKeys.length ? parentKeysSeperator : ''}${key}`]: object[key] } | |
) | |
}; | |
}, {}); | |
} | |
flattenObject(obj); | |
/// expected output { a: 10, b#c: 20, b#d: 30, b#e#f: 40 } | |
////////////////////////////////////////////////////////////////////////// | |
////////////////////////////////////////////////////////////////////////// | |
const arr = [1, [2], 3, [4, [5]]]; | |
function flattenArray(array = []) { | |
return array.reduce((acc, val) => { | |
return [...acc, ...(Array.isArray(val) ? flattenArray(val) : [val])]; | |
}, []); | |
} | |
flattenArray(arr); | |
/// expected output [1, 2, 3, 4, 5] | |
///////////////////////////////////////////////////////////////////////// | |
///////////////////////////////////////////////////////////////////////// | |
const brr = [1, 2, 3, 4, 4, 5, 6, 7, 8]; | |
function dedupe(inputArr, getKeyOf = val => val) { | |
return inputArr.reduce((acc, val) => { | |
const index = acc.findIndex(accVal => getKeyOf(accVal) === getKeyOf(val)); | |
if (index === -1) { | |
acc.push(val); | |
} | |
return acc; | |
}, []); | |
} | |
dedupe(brr); | |
/// expected outut [1, 2, 3, 4, 5, 6, 7, 8] | |
///////////////////////////////////////////////////////////////////////// | |
///////////////////////////////////////////////////////////////////////// | |
function getObjectType(obj) { | |
return Object.prototype.toString.call(obj).slice(8, -1); | |
} | |
getObjectType(undefined); // Undefined | |
getObjectType(null); // Null | |
getObjectType(7); // Number | |
getObjectType([]); // Array | |
getObjectType({}); // Object | |
/////////////////////////////////////////////////////////////////////// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment