pop.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. var _require = require('../helpers/is'),
  3. isArray = _require.isArray,
  4. isObject = _require.isObject;
  5. var deleteKeys = require('../helpers/deleteKeys');
  6. module.exports = function pop() {
  7. var _this = this;
  8. var count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  9. if (this.isEmpty()) {
  10. return null;
  11. }
  12. if (isArray(this.items)) {
  13. if (count === 1) {
  14. return this.items.pop();
  15. }
  16. return new this.constructor(this.items.splice(-count));
  17. }
  18. if (isObject(this.items)) {
  19. var keys = Object.keys(this.items);
  20. if (count === 1) {
  21. var key = keys[keys.length - 1];
  22. var last = this.items[key];
  23. deleteKeys(this.items, key);
  24. return last;
  25. }
  26. var poppedKeys = keys.slice(-count);
  27. var newObject = poppedKeys.reduce(function (acc, current) {
  28. acc[current] = _this.items[current];
  29. return acc;
  30. }, {});
  31. deleteKeys(this.items, poppedKeys);
  32. return new this.constructor(newObject);
  33. }
  34. return null;
  35. };