| 1 |
// Copyright 2018 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package collections |
| 15 |
|
| 16 |
import ( |
| 17 |
"errors" |
| 18 |
"fmt" |
| 19 |
"reflect" |
| 20 |
|
| 21 |
"github.com/gohugoio/hugo/common/hreflect" |
| 22 |
) |
| 23 |
|
| 24 |
// Complement gives the elements in the last element of ls that are not in |
| 25 |
// any of the others. |
| 26 |
// |
| 27 |
// All elements of ls must be slices or arrays of comparable types. |
| 28 |
// |
| 29 |
// The reasoning behind this rather clumsy API is so we can do this in the templates: |
| 30 |
// |
| 31 |
// {{ $c := .Pages | complement $last4 }} |
| 32 |
func (ns *Namespace) Complement(ls ...any) (any, error) { |
| 33 |
if len(ls) < 2 { |
| 34 |
return nil, errors.New("complement needs at least two arguments") |
| 35 |
} |
| 36 |
|
| 37 |
universe := ls[len(ls)-1] |
| 38 |
as := ls[:len(ls)-1] |
| 39 |
|
| 40 |
aset, err := collectIdentities(as...) |
| 41 |
if err != nil { |
| 42 |
return nil, err |
| 43 |
} |
| 44 |
|
| 45 |
v := reflect.ValueOf(universe) |
| 46 |
switch v.Kind() { |
| 47 |
case reflect.Array, reflect.Slice: |
| 48 |
sl := reflect.MakeSlice(v.Type(), 0, 0) |
| 49 |
for i := range v.Len() { |
| 50 |
ev, _ := hreflect.Indirect(v.Index(i)) |
| 51 |
if _, found := aset[normalize(ev)]; !found { |
| 52 |
sl = reflect.Append(sl, ev) |
| 53 |
} |
| 54 |
} |
| 55 |
return sl.Interface(), nil |
| 56 |
default: |
| 57 |
return nil, fmt.Errorf("arguments to complement must be slices or arrays") |
| 58 |
} |
| 59 |
} |