all files / src/ array.js

19.23% Statements 10/52
0% Branches 0/12
0% Functions 0/9
19.23% Lines 10/52
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92              1×                               1×       1×                     1×                     1×         1×                                   1×       1×       1×                   1×  
/*!
 * Copyright (C) 2017 Glayzzle (BSD3 License)
 * @authors https://github.com/glayzzle/php-transpiler/graphs/contributors
 * @url http://glayzzle.com
 */
'use strict';
 
var phpArray = function Array(items) {
  this.items = {};
  this.properties = [];
  this.length = 0;
  this.index = 0;
  // initialize the array with initial array (a real one !)
  if (items) {
    for(var i = 0; i < items.length; i++) {
      this.items[i] = [items[i], i];
      this.properties.push(i);
    }
    this.index = items.length;
    this.length = items.length;
  }
};
 
phpArray.prototype.push = function(data) {
  return this.set(this.index, data);
};
 
phpArray.prototype.pop = function() {
  var last = this.properties.pop();
  var value = this.items[last][0];
  delete this.items[last];
  this.length --;
  if (!isNaN(last)) {
    this.index --;
  }
  return value;
};
 
phpArray.prototype.shift = function() {
  var first = this.properties.shift();
  var value = this.items[first][0];
  delete this.items[first];
  this.length --;
  return value;
};
 
/**
 * @todo need a way to improve it's performance
 */
phpArray.prototype.unshift = function() {
  // silly method, reindex all numbers into the array
  // alot of writes
};
 
phpArray.prototype.set = function(key, data) {
  var numKey = parseInt(key, 10);
  if (!isNaN(numKey)) {
    key = numKey;
    if (!(key in this.items)) {
      this.index = numKey + 1;
    }
  }
  if (!(key in this.items)) {
    this.items[key] = [data, this.properties.length];
    this.properties.push(key);
    this.length ++;
  } else {
    this.items[key][0] = data;
  }
  return true;
};
 
phpArray.prototype.get = function(key) {
  return this.items[key][0];
};
 
phpArray.prototype.isset = function(key) {
  return key in this.items;
};
 
phpArray.prototype.unset = function(key) {
  if (key in this.items) {
    this.properties.splice(this.items[key][1], 1);
    delete this.items[key];
    this.length --;
    return true;
  }
  return false;
};
 
module.exports = phpArray;