###########################################################
# RapydScript Standard Library
# Author: Alexander Tsepkov
# Copyright 2013 Pyjeon Software LLC
# License: Apache License    2.0
# This library is covered under Apache license, so that
# you can distribute it with your RapydScript applications.
###########################################################


str = JSON.stringify


###########################################################
# String Methods
###########################################################
String.prototype.find = String.prototype.indexOf
String.prototype.strip = String.prototype.trim
String.prototype.lstrip = String.prototype.trimLeft
String.prototype.rstrip = String.prototype.trimRight
String.prototype.join = def(iterable):
    return iterable.join(this)
String.prototype.zfill = def(size):
    s = this
    while s.length < size:
        s = "0" + s
    return s


###########################################################
# Array Methods
###########################################################
def list(iterable=[]):
    result = []
    for i in iterable:
        result.append(i)
    return result
Array.prototype.append = Array.prototype.push
Array.prototype.find = Array.prototype.indexOf
Array.prototype.index = def(index):
    val = this.find(index)
    if val == -1:
        raise ValueError(str(index) + " is not in list")
    return val
Array.prototype.insert = def(index, item):
    this.splice(index, 0, item)
Array.prototype.pop = def(index=this.length-1):
    return this.splice(index, 1)[0]
Array.prototype.extend = def(array2):
    this.push.apply(this, array2)
Array.prototype.remove = def(item):
    index = this.find(item)
    this.splice(index, 1)
Array.prototype.copy = def():
    return this.slice(0)


###########################################################
# Dictionary Methods
###########################################################
# dict (this is a bit of a hack for now, to avoid overwriting the Object)
# the methods below must be used via dict.method(object) instead of object.method()
def dict(iterable):
    result = {}
    for key in iterable:
        result[key] = iterable[key]
    return result

if type(Object.getOwnPropertyNames) is not "function":
    # IE and older browsers
    dict.keys = def(hash):
        keys = []

        # Use a standard for in loop
        JS("""
        for (var x in hash) {
            if (hash.hasOwnProperty(x)) {
                keys.push(x);
            }
        }
        """)
        return keys
else:
    # normal browsers
    dict.keys = def(hash):
        return Object.getOwnPropertyNames(hash)

dict.values = def(hash):
    vals = []
    for key in dict.keys(hash):
        vals.append(hash[key])
    return vals

dict.items = def(hash):
    items = []
    for key in dict.keys(hash):
        items.append((key, hash[key]))
    return items

dict.copy = dict

dict.clear = def(hash):
    for key in dict.keys(hash):
        del hash[key]
