PageRenderTime 45ms CodeModel.GetById 39ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/src/erlv8_array.erl

http://github.com/beamjs/erlv8
Erlang | 52 lines | 38 code | 14 blank | 0 comment | 0 complexity | a478cc5fc0061e96818b3a8fc1273f60 MD5 | raw file
 1-module(erlv8_array).
 2
 3-include("erlv8.hrl").
 4
 5-extends(erlv8_object).
 6
 7-compile({no_auto_import,[length/1]}).
 8
 9-export([list/1, object/1, length/1, push/2, unpush/1, unshift/2, delete/2,
10
11         new/1, new/2]).
12
13list(#erlv8_array{resource = Resource, vm = VM}) ->
14    erlv8_vm:enqueue_tick(VM,{list,Resource}).
15
16object(#erlv8_array{resource = Resource, vm = VM}) ->
17    erlv8_object:new(Resource,VM).
18
19new(O) ->
20    new(O, undefined).
21
22new(O,V) ->
23    #erlv8_array{resource = O, vm = V}.
24
25length(Self) ->
26    erlang:length(list(Self)). %% TODO: I guess it will be more efficient if we had a NIF for that?
27
28push(Val, Self) ->
29    M = Self:object(),
30    M:set_value(length(Self),Val).
31
32unpush(Self) ->
33    M = Self:object(),
34    M:delete(M:length()-1).
35
36unshift(Val, Self) ->
37    M = Self:object(),
38    L = length(Self),
39    lists:foreach(fun (I) ->
40                          M:set_value(L-I,M:get_value(L-I-1))
41                  end, lists:seq(0,L-1)),
42    M:set_value(0,Val).
43
44delete(Index, Self) ->
45    M = Self:object(),
46    L = length(Self),
47    V = M:get_value(Index),
48    lists:foreach(fun (I) ->
49                          M:set_value(I,M:get_value(I+1))
50                  end, lists:seq(Index,L-1)),
51    M:set_value(length,L-1),
52    V.