Skip to content

Instantly share code, notes, and snippets.

View SergioR82's full-sized avatar

Sergio Rodriguez SergioR82

View GitHub Profile
@SergioR82
SergioR82 / Traversehybrid.js
Created November 17, 2018 22:52
Traverse with straight loop and recursion
function TraverseHybrid(bookarray, resultArray = [], currentObj = {}){
//Safe case when bookarray is not an array.
if (!Array.isArray(bookarray)) return resultArray;
//Safe case when bookarray is empty.
if (bookarray.length <= 0) return resultArray.push(currentObj);
let resultObj = {};
let data = {};
@SergioR82
SergioR82 / TraverseWithTCO.js
Created November 17, 2018 22:50
Traverse books with TCO implementation
function TraverseWithTOC([obj,...subarray], resultArray = [], currentObj = {}){
if (obj === undefined) return resultArray;
if (typeof obj === 'object' && !(isObjectEmpty(obj))){
let hasPropArray = false;
let resultObj = {};
for (let property in obj) {
if (obj.hasOwnProperty(property)) {
if (isPrimitive(obj[property]))
@SergioR82
SergioR82 / PowTCOExample.js
Last active November 17, 2018 22:25
PowExample implementation using Tail Call Optimization
function PowTCOExample(val, exp, result = 1){
//Safe case to catch all possible errors
if(val == 0 || typeof val != 'number'
|| typeof exp != 'number') return 0;
//First base case. Avoid recursivity when
//power is 0.
if(exp === 0) return 1;
@SergioR82
SergioR82 / FlatBooks.js
Last active November 13, 2018 02:22
Traverse an array of objects using recursion
let isObjectEmpty = (obj) => {
return Object.keys(obj).length === 0;
};
let isPrimitive = (element) => {
return (typeof element === 'object') ? element === null : typeof element !== 'function';
};
function TraverseRecursiveArray (myarray, pos, obj){
@SergioR82
SergioR82 / recursivePowExample.js
Last active November 11, 2018 02:09
Recursion - Raise value to power n
function PowExample(val, exp){
//Safe case to catch all possible errors
if(val == 0 || typeof val != 'number'
|| typeof exp != 'number') return 0;
//First base case. Avoid recursivity when
//power is 0.
if(exp === 0) return 1;