Last active
April 4, 2021 10:36
-
-
Save kraftdorian/1b4cc11c9d69f8dcbc8a92a5d071f2f0 to your computer and use it in GitHub Desktop.
Recursive insert sort in JavaScript written in Prolog style
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const allowedSortValueTypes = ['string', 'number', 'bigint']; | |
const usePrologStyleList = (array) => { | |
const [head, ...tail] = array; | |
return [head, tail]; | |
}; | |
const insertState = (value, list, acc, isInserted) => { | |
const [head, tail] = usePrologStyleList(list); | |
if (!allowedSortValueTypes.includes(typeof value)) { | |
throw new Error(`Value must be one of: ${allowedSortValueTypes.join(', ')}. Given: ${typeof value}`); | |
} | |
if (head === undefined) { | |
return [...acc].concat(isInserted ? [] : value); | |
} | |
if (value > head || (value <= head && isInserted)) { | |
acc = acc.concat(head); | |
} else if (value <= head && !isInserted) { | |
acc = acc.concat(value, head); | |
isInserted = true; | |
} | |
return insertState(value, tail, acc, isInserted); | |
}; | |
const insert = (value, list) => insertState(value, list, [], false); | |
const insertSortState = (list, sortedList, acc) => { | |
const [head, tail] = usePrologStyleList(list); | |
if (head === undefined) { | |
return sortedList = acc; | |
} | |
return insertSortState(tail, sortedList, insert(head, acc)); | |
}; | |
const insertSort = (list) => insertSortState(list, [], []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script is based on this Prolog program.
Use case:
Result: