Toggle navigation
?
users online
Logout
Open hangout
Open chat for current file
% JAVASCRIPT ARRAY FUNCTIONS IMPLEMENTED IN PROLOG, ONLY USING `append` and `length`. % (documentation from: https://www.w3schools.com/jsref/jsref_obj_array.asp) % includes() Check if an array contains the specified element includes(Item, List) :- append(_, [Item|_], List). % indexOf() Search the array for an element and returns its position % lastIndexOf() Search the array for an element, starting at the end, and returns its position % (indexOf already generates ALL indices of occurances of Item, so no need for lastIndexOf.) indexOf(Item, List, Index) :- append(Prefix, [Item|_], List), length(Prefix, Index). % pop() Removes the last element of an array, and returns that element pop(List, NewList) :- append(NewList, [_], List). % push() Adds new elements to the end of an array, and returns the new length push(List, NewElement, NewList) :- append(List, [NewElement], NewList). % shift() Removes the first element of an array, and returns that element shift(List, ListShifted) :- append([_], ListShifted, List). % slice() Selects a part of an array, and returns the new array slice(List, Start, End, Infix) :- Len is End - Start, length(Prefix, Start), length(Infix, Len), append(Prefix, Suffix, List), append(Infix, _, Suffix). % splice() Adds/Removes elements from an array splice(List, Index, HowMany, NewItems, NewList) :- length(Prefix, Index), length(InfixRemoved, HowMany), append(Prefix, Suffix, List), append(InfixRemoved, NewListSuffix, Suffix), append(Prefix, NewItems, NewListPrefix), append(NewListPrefix, NewListSuffix, NewList). % unshift() Adds new elements to the beginning of an array, and returns the new length unshift(List, NewElement, NewList) :- append([NewElement], List, NewList).