Skip to content

Instantly share code, notes, and snippets.

@elitenomad
Last active June 20, 2018 10:21
Show Gist options
  • Save elitenomad/15423061bc25da81c1c3e5de6727fd72 to your computer and use it in GitHub Desktop.
Save elitenomad/15423061bc25da81c1c3e5de6727fd72 to your computer and use it in GitHub Desktop.
Join elements of an array given a delimiter (Recursive and Regular loop methods)
const joinElements = (array, joiner) => {
const recurse = (index, resultSoFor = '') => {
resultSoFor += array[index];
if (index == array.length - 1) {
return resultSoFor;
} else {
resultSoFor = resultSoFor + joiner;
return recurse(index + 1, resultSoFor);
}
};
return recurse(0, '');
};
const joinElementsRegularLoop = (array, joiner) => {
let resultSoFor = '';
array.forEach((element, index) => {
resultSoFor += array[index];
if (index != array.length - 1) {
resultSoFor = resultSoFor + joiner;
}
});
return resultSoFor;
};
const result = joinElements(['s', 'cr', 't', 'cod', ' :):)'], 'e');
console.log(result);
const resultForRegularLoop = joinElementsRegularLoop(
['s', 'cr', 't', 'cod', ' :):)'],
'e'
);
console.log(resultForRegularLoop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment