PageRenderTime 16ms CodeModel.GetById 1ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 1ms

/modules/mod_base/filters/filter_first.erl

https://code.google.com/p/zotonic/
Erlang | 49 lines | 25 code | 8 blank | 16 comment | 0 complexity | 63423f2f012585260cfcb22b262861b3 MD5 | raw file
 1%% @author Marc Worrell <marc@worrell.nl>
 2%% @copyright 2010 Marc Worrell
 3%% @doc 'first' filter, return the first element in a string or list
 4
 5%% Copyright 2010 Marc Worrell
 6%%
 7%% Licensed under the Apache License, Version 2.0 (the "License");
 8%% you may not use this file except in compliance with the License.
 9%% You may obtain a copy of the License at
10%% 
11%%     http://www.apache.org/licenses/LICENSE-2.0
12%% 
13%% Unless required by applicable law or agreed to in writing, software
14%% distributed under the License is distributed on an "AS IS" BASIS,
15%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16%% See the License for the specific language governing permissions and
17%% limitations under the License.
18
19-module(filter_first).
20-export([
21    first/2,
22    first/3
23]).
24
25-include("zotonic.hrl").
26
27first(undefined, _Context) ->
28    undefined;
29first(<<First, _/binary>>, _Context) ->
30    First;
31first(Other, Context) ->
32    case erlydtl_runtime:to_list(Other, Context) of
33        [] -> <<>>;
34        [H|_] -> H
35    end.
36
37first(undefined, _Length, _Context) ->
38    undefined;
39first(Value, Length, Context) ->
40    first1(erlydtl_runtime:to_list(Value, Context), Length, []).
41
42
43first1([], _N, Acc) ->
44    lists:reverse(Acc);
45first1(_L, 0, Acc) ->
46    lists:reverse(Acc);
47first1([H|T], N, Acc) ->
48    first1(T, N-1, [H|Acc]).
49