Skip to content

Instantly share code, notes, and snippets.

@jaymecd
Last active May 12, 2019 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaymecd/d9ef76a8084c7fd936e177a2afe781bc to your computer and use it in GitHub Desktop.
Save jaymecd/d9ef76a8084c7fd936e177a2afe781bc to your computer and use it in GitHub Desktop.
ES6 training
const substr = (str, start = 0, length = str.length) => {
if (start === 0 && length === str.length) {
return str;
}
if (start > str.length || length <= 0) {
return '';
}
const startIndex = (start < 0) ? Math.max(0, str.length - Math.abs(start)) : start;
const stopIndex = Math.min(str.length, startIndex + length);
let result = '';
for (let i = startIndex; i < stopIndex; i++) {
result += str[i];
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment