Hands-On Data Structures and Algorithms with JavaScript
上QQ阅读APP看书,第一时间看更新

Using the stack

To use the Stack class created previously, you would have to make a minor change to allow the stack to be used based on the environment in which you are planning to use it. Making this change generic is fairly straightforward; that way, you do not need to worry about multiple environments to support and can avoid repetitive code in each application:

// AMD
if (typeof define === 'function' && define.amd) {

define(function () { return Stack; });

// NodeJS/CommonJS

} else if (typeof exports === 'object') {

if (typeof module === 'object' && typeof module.exports ===
'object') {

exports = module.exports = Stack;
}

// Browser

} else {

window.Stack = Stack;
}

Once we add this logic to the stack, it is multi-environment ready. For the purpose of simplicity and brevity, we will not add it everywhere we see the stack; however, in general, it's a good thing to have in your code.

If your technology stack comprises ES5, then you need to transpile the preceding stack code to ES5. This is not a problem, as there are a plethora of options available online to transpile code from ES6 to ES5.