shift.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 shift() {
  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.shift();
  15. }
  16. return new this.constructor(this.items.splice(0, count));
  17. }
  18. if (isObject(this.items)) {
  19. if (count === 1) {
  20. var key = Object.keys(this.items)[0];
  21. var value = this.items[key];
  22. delete this.items[key];
  23. return value;
  24. }
  25. var keys = Object.keys(this.items);
  26. var poppedKeys = keys.slice(0, 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. };