Skip to content

Commit

Permalink
fix: List functions handle invalid position
Browse files Browse the repository at this point in the history
List functions should return null if the position is zero. A position must be positive or negative but not zero.

(cherry picked from commit 6bf385f)
  • Loading branch information
saig0 committed Jan 21, 2025
1 parent f8eb445 commit 7a2c063
Showing 1 changed file with 31 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -273,20 +273,26 @@ class ListBuiltinFunctions(private val valueMapper: ValueMapper) {
private def sublistFunction =
builtinFunction(
params = List("list", "start"),
invoke = { case List(ValList(list), ValNumber(start)) =>
ValList(list.slice(listIndex(list, start.intValue), list.length))
invoke = {
case List(ValList(_), ValNumber(start)) if start == 0 =>
ValError("start position must be a non-zero number")
case List(ValList(list), ValNumber(start)) =>
ValList(list.slice(listIndex(list, start.intValue), list.length))
}
)

private def sublistFunction3 = builtinFunction(
params = List("list", "start", "length"),
invoke = { case List(ValList(list), ValNumber(start), ValNumber(length)) =>
ValList(
list.slice(
listIndex(list, start.intValue),
listIndex(list, start.intValue) + length.intValue
invoke = {
case List(ValList(_), ValNumber(start), ValNumber(_)) if start == 0 =>
ValError("start position must be a non-zero number")
case List(ValList(list), ValNumber(start), ValNumber(length)) =>
ValList(
list.slice(
listIndex(list, start.intValue),
listIndex(list, start.intValue) + length.intValue
)
)
)
}
)

Expand Down Expand Up @@ -323,23 +329,29 @@ class ListBuiltinFunctions(private val valueMapper: ValueMapper) {

private def insertBeforeFunction = builtinFunction(
params = List("list", "position", "newItem"),
invoke = { case List(ValList(list), ValNumber(position), newItem: Val) =>
ValList(
list
.take(listIndex(list, position.intValue)) ++ (newItem :: Nil) ++ list
.drop(listIndex(list, position.intValue))
)
invoke = {
case List(ValList(_), ValNumber(position), _) if position == 0 =>
ValError("position must be a non-zero number")
case List(ValList(list), ValNumber(position), newItem: Val) =>
ValList(
list
.take(listIndex(list, position.intValue)) ++ (newItem :: Nil) ++ list
.drop(listIndex(list, position.intValue))
)
}
)

private def removeFunction = builtinFunction(
params = List("list", "position"),
invoke = { case List(ValList(list), ValNumber(position)) =>
ValList(
list.take(listIndex(list, position.intValue)) ++ list.drop(
listIndex(list, position.intValue + 1)
invoke = {
case List(ValList(_), ValNumber(position)) if position == 0 =>
ValError("position must be a non-zero number")
case List(ValList(list), ValNumber(position)) =>
ValList(
list.take(listIndex(list, position.intValue)) ++ list.drop(
listIndex(list, position.intValue + 1)
)
)
)
}
)

Expand Down

0 comments on commit 7a2c063

Please sign in to comment.